思路:
滑动窗口:
使用两个指针 left 和 right 表示窗口的左右边界。
right 指针用于扩展窗口,left 指针用于收缩窗口。
哈希集合:
使用一个哈希集合 charSet 来存储当前窗口中的字符,确保字符不重复。
遍历字符串:
移动 right 指针,将字符加入 charSet。
如果字符已经存在于 charSet 中,移动 left 指针,直到重复字符被移除。
在每次移动 right 指针后,更新最大长度。
#include <string>
#include <unordered_set>
#include <algorithm>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length();
int maxLen = 0; // 记录最大长度
int left = 0; // 滑动窗口的左边界
unordered_set<char> charSet; // 用于存储当前窗口中的字符
for (int right = 0; right < n; ++right) {
// 如果当前字符已经存在于集合中,移动左边界
while (charSet.find(s[right]) != charSet.end()) {
charSet.erase(s[left]);
left++;
}
// 将当前字符加入集合
charSet.insert(s[right]);
// 更新最大长度
maxLen = max(maxLen, right - left + 1);
}
return maxLen;
}
};
时间复杂度:𝑂(𝑛)
效果不是特别好