approach 1
sliding window
we can use a window to maintain the current max substring. when sliding right, we are adding a new character in the window, so we need to check if this character is in the current window, if do, we should cut the window to the right side of that character.
C++ code
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> wd;
int res = 0;
for (int i = 0, j = 0; i < s.size(); i++) {
while (wd[s[i]]) wd[s[j++]]--;
wd[s[i]]++;
res = max(res, i - j + 1);
}
return res;
}
};