這題的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;
}
}