159 Longest Substring with At Most Two Distinct Characters

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值