Longest Substring with At Most Two Distinct Characters

本文介绍了一种使用快慢指针与哈希表相结合的方法来解决LeetCode上的一道题目:寻找字符串中最长的包含最多两个不同字符的子串。通过不断移动尾指针并更新哈希表,当哈希表大小超过2时则收缩头指针直至满足条件,最终找到符合条件的最长子串。

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

Given a string, find the length of the longest substring T that contains at most 2 distinct characters.

For example,Given s = “eceba”,

T is "ece" which its length is 3.

public int lengthOfLongestSubstringTwoDistinct(String s)


这一题其实和 http://blog.youkuaiyun.com/chaochen1407/article/details/42238259(Longest substring without repeating character)是同出一辙的。用快慢指针来表示当前窗口的头尾,用一个哈希表来维护窗口的内容。尾指针不断前行,然后将内容放进哈希表里维护。当哈希表的size > 2的时候头指针就不断收缩直到哈希表的size回归2为止。然后在这个过程里维护一个最大长度值即可。给出代码如下:

    public int lengthOfLongestSubstringTwoDistinct(String s) {
        HashMap<Character, Integer> cached = new HashMap<Character, Integer>();
        int head = 0;
        int res = 0;
        for(int i = 0; i < s.length(); i++){
            if(cached.containsKey(s.charAt(i))){
                cached.put(s.charAt(i), cached.get(s.charAt(i)) + 1);
                res = Math.max(res, i - head + 1);
            }else{
                int cur_res = i - head + 1;
                cached.put(s.charAt(i), 1);
                cur_res = cached.size() > 2 ? cur_res - 1 : cur_res;
                res = Math.max(res, cur_res);
                while(cached.size() > 2){
                    Character head_c = s.charAt(head);
                    cached.put(head_c, cached.get(head_c) - 1);
                    if(cached.get(head_c) == 0)
                        cached.remove(head_c);
                    head++;
                }
            }
        }
        return res;
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值