The naive solution is to check all substrings and calculate the number of distinct characters they have. if the length of the string is n, then the time complexity of this solution will be n(n+1)n/ 2, which is n^3.
As it also reminds of another problem that I have solved recently: longest substring without any repeating characters. That problem was solved by using hashmap/hashset. So I decided to use hashset to solve this one too. The naive solution was implemented as below but got a TLE as expected.
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) {
return 0;
}
List<String> list = findAllSubStrings(s);
int max = Integer.MIN_VALUE;
for (String str : list) {
if (distinctCharacters(str)) {
max = Math.max(str.length(), max);
}
}
return max;
}
public List<String> findAllSubStrings(String s) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < s.length(); i++) {
for (int j = i; j <= s.length(); j++) {
list.add(s.substring(i, j));
}
}
return list;
}
public boolean distinctCharacters(String s) {
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (!set.contains(s.charAt(i))) {
if (set.size() == 2) {
return false;
} else {
set.add(s.charAt(i));
}
}
}
return true;
}
}
Now it’s time to think of a more efficient solution…after searching on the web I found there is one solution using pointers.
I refer to this solution https://codesolutiony.wordpress.com/2015/05/22/lintcode-longest-substring-with-at-most-k-distinct-characters/
I like this solution because it provides us with a template. Below is the code. It’s almost the same with the one above, but with some notes
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int start = 0;
int result = 1;
Map<Character, Integer> map = new HashMap<Character, Integer>();
//eceba
for (int end = 0; end < s.length(); end++) {
char current = s.charAt(end); //e
if (map.containsKey(current)) {
map.put(current, map.get(current) + 1); //map : {e, 2} {c,1}
} else {
if (map.size() == 2) {
result = Math.max(result, end - start); // result = 3
for (int i = start; i < end; i++) {
map.put(s.charAt(i), map.get(s.charAt(i)) - 1);
start++;
//本解法最关键的一步!!!不难理解此事窗口大小为k-1。但是不好理解为什么此时start就是正确的
if (map.get(s.charAt(i))== 0) { //when i = 2, char = c
map.remove(s.charAt(i)); //{e, 2}
break;
}
}
}
map.put(current, 1);
}
}
result = Math.max(result, s.length() - start);
return result;
}
}