3. 无重复字符的最长子串

leetcode-3. 无重复字符的最长子串

这道题最主要的考察点还是滑动窗口,但是刚刚学习了C++中的哈希表用法,练习一下api调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int fastIndex = 0, slowIndex = 0, size = 0;
int maxSize = 0;
unordered_set<char> words;
while(fastIndex < s.size())
{
if(words.count(s[fastIndex]) == 0)
{
words.insert(s[fastIndex]);
fastIndex++;
size++;
if(size > maxSize)
maxSize++;
}
else
{
while(words.count(s[fastIndex]) != 0)
{
words.erase(s[slowIndex]);
slowIndex++;
size--;
}
}
}
return maxSize;
}
};