Given astring, 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.
C++版
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int n = s.length();
int i=0,j=0; ///两个指针,i始终指向新的字串开头,j一直往后走.
int maxLen = 0;
bool exist[256] = {false};
for(;j <n ; j++) {
if (exist[s[j]]) {
maxLen = max(maxLen, j-i);
while (s[i] != s[j]) {
exist[s[i]] = false;
i++;
}
i++;
} else {
exist[s[j]] = true;
}
}
return max(maxLen, j-i);
}
};
Java版
public class Solution {
public int lengthOfLongestSubstring(String s) {
boolean[] exist = new boolean[256];
int i = 0, j = 0, maxLen = 0;
for (; j < s.length(); j++) {
while (exist[s.charAt(j)]) {
exist[s.charAt(i)] = false;
i++;
}
exist[s.charAt(j)] = true;
maxLen = Math.max(j - i + 1, maxLen);
}
return maxLen;
}
}