3. Longest Substring Without Repeating Characters
Description
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.
思路
我们可以采取扫描法。 刚开始将i, j指针指向位置0,然后往后移动j指针直到序列出现重复,此时更新答案,完后移动i指针使得[i, j)区间内没有重复,继续上述操作。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = 0;
int count[300];
memset(count, 0, sizeof(count));
int i=0, j=0;
while(1) {
while(count[s[j]] == 0 && j<s.length()) {
count[s[j]]++;
j++;
}
res = max(res, j-i);
if(j == s.length()) break;
while(s[i] != s[j]) {
count[s[i]]--;
i++;
}
count[s[i]]--;
i++;
}
return res;
}
};