2026/03/01

[LeetCode] 3 Longest Substring Without Repeating Characters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
  int lengthOfLongestSubstring(string s) {
    int left = 0;
    int right = 0;
    int ans = 0;
    unordered_set<char> used;

    while (right < s.length()) {
      if (!used.count(s[right])) {
        used.insert(s[right]);
        ans = max(ans, right - left + 1);
        right++;
      }
      else {
        while(used.count(s[right]) && left <= right) {
          used.erase(s[left]);
          left++;
        }
      }
    }
    return ans;
  }
};