#include <unordered_set>
int lengthOfLongestSubstring(string s) {
int n = s.length();
unordered_set<char> charSet; // 用于存储当前窗口中的字符
int maxLength = 0;
int left = 0;
for (int right = 0; right < n; right++) {
// 如果当前字符已经存在于集合中,移动左指针
while (charSet.find(s[right]) != charSet.end()) {
charSet.erase(s[left]);
left++;
}
// 将当前字符加入集合
charSet.insert(s[right]);
// 更新最大长度
maxLength = max(maxLength, right - left + 1);
}
return maxLength;
}
最长无重复字串
于 2023-04-21 11:36:40 首次发布