Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
思路:兩個指針:begin和end。begin指向無重複字符的子串的頭,end指向無重複支付的子串的尾。
一個整型數組:charIndices,長度爲128(ascii字符有128個),每一位保存對應字符出現在s中的位置。
從頭遍歷s,若charIndices中當前字符對應的值大於begin,表示子串中出現了重複字符。此時,判斷子串長度,並將begin指向重複字符的下一位。最後將當前字符的位置保存在整型數組中。
遍歷完成後不要忘記再判斷子串長度。
Java代碼:
public int lengthOfLongestSubstring(String s) {
if(s.equals("")) return 0 ;
int[] charIndices = new int[128] ;
for(int i = 0 ;i < charIndices.length ;i ++) charIndices[i] = -1 ;
int begin = 0 ;
int end = 0 ;
int index = -1;
int length = 0 ;
for(int i = 0;i < s.length() ; i++){
end = i ;
index = (int)s.charAt(i) ;
if(charIndices[index] >= begin){
if(end - begin > length){
length = end - begin ;
}
begin = charIndices[index] + 1 ;
}
charIndices[index] = i ;
}
if(end + 1 - begin > length){
length = end + 1 - begin ;
}
return length ;
}