这题的idea就是从前往后扫,用个hashtable(其实是数组)把上次出现过的位置记下来,遇到出现过的,就从上次出现过的地方开始往下算。 具体实现细节对于新手还是有些坑,比如我刚开始就觉得从新的start开始扫的话,要把hashtable重新initialize,但实际上加一个条件就能避免。另外最长substring出现在最后也有点费思量。还有hashtable要initialize 为-1等也需要注意。
public class Solution {
public int lengthOfLongestSubstring(String s) {
int start = 0, max = 0;
int [] last = new int[256];
Arrays.fill(last, -1); //initialize as -1, since 0 is also a valid position.
for (int i = 0; i < s.length(); i++){
int c = s.charAt(i);
if (last[c] >= start){ //with this check, you don't need to count the appreance again.
max = Math.max(max, i - start);
start = last[c] + 1;
}
last[c] = i;
}
max = Math.max(max, s.length() - start); //don't forget the last character, like "abcd"
return max;
}
}