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.
int lengthOfLongestSubstring(string s) {
int ans= 0, l = 0 ;
int map[256] = {0};
for(int i = 0 ; i < s.size(); i ++) {
if(map[s[i]] != 0 && map[s[i]] >= l) {
ans= (i - l) > ans ? (i - l) : ans;
l = map[s[i]] ;
}
if( i + 1 - l > ans) ans= i + 1 - l ;
map[s[i]] = i + 1 ;
}
return anw;
}
看起来更加牛B 的代码是这个:
int lengthOfLongestSubstring(string s) {
int n = s.size(), ans = 0;
int index [128] = {0}; // current index of character
// try to extend the range [i, j]
for (int j = 0, l = 0; j < n; j++) {
l = std::max(index[s[j]], l);
ans = std::max(ans, j - l + 1);
index[s[j]] = j + 1;
}
return ans;
}