
解法 动态规化
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0) return 0;
char[] chars = s.toCharArray();
return lengthOfLongestSubstring(chars);
}
private int lengthOfLongestSubstring(char[] chars) {
// f(i)代表以第i个字符结尾,不包含重复字符的子字符串的最大长度
// 不含重复字符的子字符串的最大长度
int maxLength = 0;
// f(i-1)
int curLength = 0;
// 数组用于记录任意字符之前出现的位置,ASCII码表一个128个字符
int[] position = new int[128];
Arrays.fill(position,-1);
for(int i = 0; i < chars.length; ++i) {
// 第i个字符之前出现的位置
int preIndex = position[chars[i]];
// 第i个字符之前没有出现过,或者第i个字符与它上次出现位置的距离大于f(i-1)
if(preIndex < 0 || i - preIndex > curLength) {
curLength++;
// 第i个字符出现在f(i-1)对应的子字符串之中
}else {
if(curLength > maxLength)
maxLength = curLength;
curLength = i - preIndex;
}
position[chars[i]] = i;
}
if(curLength > maxLength)
maxLength = curLength;
return maxLength;
}
}
版权声明:本文为renweiyi1487原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。