思路
哈希表+滑动窗口
-
枚举子串的首字母,寻找最长不包含重复字符的最长的子串,这个过程就是low指针不变,high指针不停右移,直到下一次字符使它出现重复,这时更换首字母,让low指针右移,.再重复上面high指针右移原则。
分析:这个过程,high指针不需要左移,eg, "(abc)abcbb"中“abc”不包含重复,那么“bc”也一定不包含,当high指针不用向左移动,枚举low指针,就可以使用滑动窗口。 -
可以使用无序哈希表 unordered_map来记录子串的字母,用map.count(key)来确定key之前是否已经记录,来检验重复。
对应的代码和注释如下
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int low = 0,high=0;
int res=0;
unordered_map<int, int> ha;
for (int low = 0; low < s.length(); low++)
{//移动low指针
while (high < s.length() && !ha.count(s[high]))
{//移动high指针
ha[s[high]] = 1;
high++;
}
res = max(res, high - low);
ha.erase(s[low]);
}
return res;
}
};