Discription
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记录左边界,一个指针right记录右边界。
向右滑动右边界:
- 如果right所指元素即 s[right] 未曾出现过,则记录该元素的位置 hash[s[right]] = right;
- 如果right所指元素即 s[right] 出现过,且上一次出现在左边界以左,即 hash[s[right]] < left,更新 hash[s[right]] = right 为最近出现的位置;
- 如果right所指元素即 s[right] 出现过,且上一次出现在左边界以右(包括左边界),即 hash[s[right]] >= left,则 s[left : right-1] 为一可行解,更新最大长度以及左边界 left = left + 1;
时间复杂度:
O(n)
空间复杂度:
O(1)
代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> hash;
int begin = 0, max_len = 0, i;
for (i = 0; i < s.size(); i++)
{
if (hash.find(s[i]) == hash.end()) //第一次出现
hash[s[i]] = i;
else if (hash[s[i]] >= begin)
{
max_len = max(max_len, i - begin);
begin = hash[s[i]] + 1;
hash[s[i]] = i;
}else
hash[s[i]] = i;
}
max_len = max(max_len, i - begin); //边界条件
return max_len;
}
};
特殊样例
“”
“c”