-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongsubstring.cpp
More file actions
30 lines (29 loc) · 1.08 KB
/
Copy pathlongsubstring.cpp
File metadata and controls
30 lines (29 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int mx = 0;
int i = 0, j = 0;
unordered_map<char, int> mp;
while(j < s.length()){
mp[s[j]]++;
if(mp.size() > j-i+1){
j++;
}
else if(mp.size() == j-i+1){
mx = max(mx, j-i+1);
j++;
}
else if(mp.size() < j - i + 1) {// Triggered when duplicates are present
while(mp.size() < j - i + 1) { // Shrink window until no duplicates
mp[s[i]]--; // Decrement frequency of the leftmost character
if(mp[s[i]] == 0) { // If frequency becomes zero, remove it
mp.erase(s[i]);
}
i++; // Move the left pointer
}
j++; // Move the right pointer
}
}
return mx;
}
};