Last active
October 8, 2018 02:02
-
-
Save Helenyin123/29838eb4c44bddc7945b7bcef492701a to your computer and use it in GitHub Desktop.
340. Longest Substring with At Most K Distinct Characters
This file contains hidden or 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
| public int lengthOfLongestSubstringKDistinct(String s, int k) { | |
| Map<Character, Integer> map = new HashMap<>(); | |
| if (s == null || s.length() == 0 || k == 0) return 0; | |
| int start = 0; | |
| int longest = 0; | |
| for (int i = 0; i < s.length(); i++) { | |
| if (map.containsKey(s.charAt(i)) || map.size() < k) { | |
| map.put(s.charAt(i), i); | |
| } else { | |
| int minPos = getMinPos(map); | |
| start = minPos + 1; | |
| map.put(s.charAt(i), i); | |
| } | |
| longest = Math.max(longest, i - start + 1); | |
| } | |
| return longest; | |
| } | |
| private int getMinPos(Map<Character, Integer> map) { | |
| Map.Entry<Character, Integer> result = null; | |
| for (Map.Entry<Character, Integer> entry : map.entrySet()) { | |
| if (result == null || entry.getValue() < result.getValue()) { | |
| result = entry; | |
| } | |
| } | |
| map.remove(result.getKey()); | |
| return result.getValue(); | |
| } |
This file contains hidden or 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
| /** | |
| follow up: How about stream input (infinite input) 用Mapreduce | |
| follow upup: Any other solution? KMP | |
| */ | |
| public int lengthOfLongestSubstringKDistinct(String s, int k) { | |
| if(s.length() == 0 || k == 0) return 0; | |
| int[] letters = new int[128]; | |
| int count = 0, i = 0, j = 0, max = 0; | |
| while(j < s.length()) { | |
| if(++letters[s.charAt(j)] == 1) count++; | |
| while(count > k) { | |
| if(--letters[s.charAt(i)] == 0) count--; | |
| i++; | |
| } | |
| max = Math.max(max, j-i+1); | |
| j++; | |
| } | |
| return max; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment