LC159-最多包含两个不同字符的最长子串

题目

  • 给定一个字符串 s ,找出 至多 包含两个不同字符的最长子串 t 。

  • 示例 1:
    输入: “eceba”
    输出: 3
    解释: t 是 “ece”,长度为3。

  • 示例 2:
    输入: “ccaabbb”
    输出: 5
    解释: t 是 “aabbb”,长度为5。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-with-at-most-two-distinct-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        Set<Character> set =new HashSet<>();
        int res = 0;
        for(int i = 0;i<s.length();i++){
            set.clear();
            int count =0;
            for(int j =i;j<s.length();j++){
                //如果在集合里,则count++;
                 if(set.contains(s.charAt(j))){  
                    count++;
                    res =Math.max(res,count);
                }
                //如果不在集合且集合大小小于2,把元素加入且count++
                else if(set.size()<2){
                    set.add(s.charAt(j));
                     count++;
                    res =Math.max(res,count);
                }
                //不满足情况,跳出本次循环
                else{
                    break;
                }
            }
        }
        return res;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值