Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
思路一
用 map储存 key为字符,value 为这个字符的位置,我们可以维护一个子字符串(无重复字符),记录它的起始位置,遍历 string s 当无法在map中找到字符或者小于子字符串的起始位置,就是没有在这个字符串中出现,反之则字符重复,不过 map查找为 O(lgn),因此总的时间复杂度为O(NlgN)
int lengthOfLongestSubstring1(string s) {
int i = 0, length = s.length();
//set<char> set1;
map<int, int> m;
int len = 0;
int max_len = 0;
int sub_strart = 0;
for (i = 0; i < length; i++) {
if (m.find(s[i]) == m.end()) {// can't search
len++;
} else {
int pos = m[s[i]];
max_len = max(len, max_len);
len = len - (pos - sub_strart);
sub_strart = pos + 1;
}
m[s[i]] = i;
}
return max(len, max_len);
}
思路二:滑动窗口法
用一个能表示所有字符的数组b表达s中字符访问标志 right右滑遍历字符串
int lengthOfLongestSubstring(string s) {
if (s.length() == 0)
return 0;
int left = 0, right = 0;
bool b[128]={false};
int max_len = 0;
int n = s.length();
while (right < n) {
if (b[s[right]] == false) { //未访问过
b[s[right]] = true;
right++;
} else { // 访问过
max_len=max(max_len,right-left);
while(left<right && s[left]!=s[right]){
b[s[left]]= false;
left++;
}
left++;
right++;
}
}
return max(max_len,right-left);
}