Skip to content

Instantly share code, notes, and snippets.

@ahmedash95
Created April 5, 2024 14:36
Show Gist options
  • Save ahmedash95/04206cec3e0df66f65200a082e8ec65b to your computer and use it in GitHub Desktop.
Save ahmedash95/04206cec3e0df66f65200a082e8ec65b to your computer and use it in GitHub Desktop.
159. Longest Substring with At Most Two Distinct Characters
class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
int ans = 0;
int left = 0;
Map<Character, Integer> freq = new HashMap<>();
for(int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
freq.put(c, freq.getOrDefault(c, 0) + 1);
while(freq.size() > 2) {
char lc = s.charAt(left);
freq.put(lc, freq.get(lc) - 1);
if(freq.get(lc) == 0)
freq.remove(lc);
left++;
}
ans = Math.max(ans, right - left + 1);
}
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment