Longest Substring with At Most K Distinct Characters
This is a problem asked by Google.
Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains 2 unique character is "bcbbbbcccb".
1. Longest Substring Which Contains 2 Unique Characters
In this solution, a hashmap is used to track the unique elements in the map. When a third character is added to the map, the left pointer needs to move right.
You can use "abac" to walk through this solution.
public int lengthOfLongestSubstringTwoDistinct(String s) { int max=0; HashMap<Character,Integer> map = new HashMap<Character, Integer>(); int start=0; for(int i=0; i<s.length(); i++){ char c = s.charAt(i); if(map.containsKey(c)){ map.put(c, map.get(c)+1); }else{ map.put(c,1); } if(map.size()>2){ max = Math.max(max, i-start); while(map.size()>2){ char t = s.charAt(start); int count = map.get(t); if(count>1){ map.put(t, count-1); }else{ map.remove(t); } start++; } } } max = Math.max(max, s.length()-start); return max; } |
Now if this question is extended to be "the longest substring that contains k unique characters", what should we do?
2. Solution for K Unique Characters
The following solution is corrected. Given "abcadcacacaca" and 3, it returns "cadcacacaca".
public int lengthOfLongestSubstringKDistinct(String s, int k) { int result = 0; int i=0; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for(int j=0; j<s.length(); j++){ char c = s.charAt(j); if(map.containsKey(c)){ map.put(c, map.get(c)+1); }else{ map.put(c, 1); } if(map.size()<=k){ result = Math.max(result, j-i+1); }else{ while(map.size()>k){ char l = s.charAt(i); int count = map.get(l); if(count==1){ map.remove(l); }else{ map.put(l, map.get(l)-1); } i++; } } } return result; } |
Time is O(n).
<pre><code> String foo = "bar"; </code></pre>
-
Devanaboina Dinesh
-
Abhishek Ranjan
-
Abhishek Ranjan
-
Abhishek Ranjan
-
Robin
-
Jageloo Yadav
-
Ivan Grøn
-
Syed Suhail
-
Swarvanu Sengupta
-
William S
-
M Gori
-
Bukary Kandeh
-
rkho
-
rkho
-
Gurmeet Singh
-
West
-
SR
-
mg
-
mg
-
Atif Anowar Atif
-
lingyong
-
Trung Vo
-
William Kuo
-
rupalph
-
Mike
-
Mike
-
Cherry Zhao
-
Juan Melo
-
Larry Okeke
-
Shobhit Jaiswal
-
Pritika Mehta
-
up23
-
ryanlr
-
Dylan Wang
-
Satish
-
Vladimir Kravtsov
-
jason zhang
-
Anony
-
neer1304
-
guest
-
ryanlr
-
Tiago Pinho
-
Guest
-
no-nested-loops
-
Jeffery yuan
-
Yi Wang
-
skra
-
Krzysztof Rajda
-
Krzysztof Rajda
-
ashish yadav
-
xiayu5945
-
Rang-ji Hu
-
Pulkit
-
jason