159. Longest Substring with At Most Two Distinct Characters

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/

String: Sliding Window

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
int len=s.length();
if(len<3)return len;

int left=0,right=0;
HashMap<Character,Integer> hashmap=new HashMap<>();
int maxLen=2;
while(right<len){
if(hashmap.size()<3) hashmap.put(s.charAt(right),right++);
if(hashmap.size()==3){
int delIdx=Collections.min(hashmap.values());
hashmap.remove(s.charAt(delIdx));
left=delIdx+1;
}
maxLen=Math.max(maxLen,right-left);
}
return maxLen;
}
}

LeetCode Explanation

0%