Created
April 5, 2024 14:36
-
-
Save ahmedash95/04206cec3e0df66f65200a082e8ec65b to your computer and use it in GitHub Desktop.
159. Longest Substring with At Most Two Distinct Characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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