題目如下:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.
解題思路:
找出數組中最長的字數組(無重複項)問題。
思路1:對數組遍歷,遍歷的同時將字數組存在map中,如果map中出現重複的字符ch時,將map中ch及其之前的刪除,循環操作。如下圖:
map裏的變化:
結果是超時,改變一種思路。
思路2:利用一個exist數組保存字符是否出現(假設char set是ascii),從前向後遍歷數組,如果遇到已存在的字符,應該回退到這個字符上次出現的下一個位置從新開始統計(如下圖),同時注意exist數組的同步更新。
該方法來自:http://my.oschina.net/jdflyfly/blog/283405
提交代碼:
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0)
return 0;
int res = 1;
boolean[] exist = new boolean[256];
int start = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (exist[ch]) {
res = Math.max(res, i - start);
for (int k = start; k < i; k++) {
if (s.charAt(k) == ch) {
start = k + 1;
break;
}
exist[s.charAt(k)] = false;
}
} else
exist[ch] = true;
}
res = Math.max(res, s.length() - start);
return res;
}