class Solution
{
public:
int lengthOfLongestSubstring(string s)
{
unordered_set<char> set;
int len = s.size();
int right = 0;
int count = 0;
for (int i = 0; i < len; ++i)
{
if (i != 0)
{
set.erase(s[i - 1]);
}
while (right < len && !set.count(s[right]))
{
set.insert(s[right]);
++right;
}
count = max(count, right - i);
}
return count;
}
};
时间复杂度:O(N),其中 N 是字符串的长度。左指针和右指针分别会遍历整个字符串一次
空间复杂度:O(∣Σ∣),其中 Σ 表示字符集(即字符串中可以出现的字符),∣Σ∣ 表示字符集的大小。在本题中没有明确说明字符集,因此可以默认为所有 ASCII 码在 [0,128) 内的字符,即 ∣Σ∣=128。我们需要用到哈希集合来存储出现过的字符,而字符最多有 ∣Σ∣ 个,因此空间复杂度为 O(∣Σ∣)