Tuesday, January 23, 2018

LeetCode 159. Longest Substring with At Most Two Distinct Characters - Google - HashMap, Two Pointers, String

The main idea is to maintain a sliding window with 2 unique characters. 
The key is to store the last occurrence of each character as the value in the hashmap.

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



class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
// filter abnormal inputs
if (s == null) {
return 0;
}
if (s.length() < 3) {
return s.length();
}
// core logic
int start = 0;
int end = 0;
int maxLength = Integer.MIN_VALUE;
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0; i < s.length(); i++) {
Character key = s.charAt(i);
if (!map.containsKey(key) && map.size() == 2) {
// situation 3
int leftMost = Integer.MAX_VALUE;
for(int value: map.values()) {
leftMost = Math.min(leftMost, value);
}
start = leftMost + 1;
map.remove(s.charAt(leftMost));
}
map.put(key, end);
maxLength = Math.max(maxLength, end - start + 1);
end++;
}
return maxLength;
}
}

No comments:

Post a Comment