feat: 3_longest_substring_without_repeating_characters

This commit is contained in:
SquidSpirit 2025-02-12 00:06:20 +08:00
parent 7e8424b0e9
commit 37cab2ead6

View File

@ -0,0 +1,35 @@
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxLen = 0, currentLen = 0;
queue<int> substr;
unordered_set<int> charset;
for (int index = 0; index < s.length(); index++) {
char currentChar = s[index];
// has repeat
if (charset.find(currentChar) != charset.end()) {
while (substr.front() != currentChar) {
charset.erase(substr.front());
substr.pop();
currentLen--;
}
charset.erase(currentChar);
substr.pop();
currentLen--;
}
charset.emplace(currentChar);
substr.emplace(currentChar);
currentLen++;
maxLen = max(maxLen, currentLen);
}
return maxLen;
}
};