題目
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.
答案
從左到右掃描佩耳,記錄當前出現過的字符,如果碰到重復字符,left = left + 1,繼續(xù)往右邊掃描
最后記得取Math.max(res, s.length() - start);
public class Solution {
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;
}
}