[LeetCode]340.最多有K个不同字符的最长子串

75 篇文章 0 订阅

题目

340.最多有K个不同字符的最长子串

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

Example 1:

Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.
Example 2:

Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.




方法1:Map统计数量+滑动窗口

        public int lengthOfLongestSubstringKDistinct(String s, int k) {
            int res = 0;
            Map<Character, Integer> map = new HashMap<>();//k:字符,v:字符出现的次数
            int l = 0;//左边窗口的位置
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                map.put(c, map.getOrDefault(c, 0) + 1);
                while (map.size() > k) {//字符的个数已经超过k个了,开始缩小左边窗口
                    char lc = s.charAt(l++);//left char
                    int t = map.get(lc) - 1;//left char的数量
                    if (t == 0) {//数量为0的时候,key被移除
                        map.remove(lc);
                    } else {
                        map.put(lc, t);//-1后数量再次更新进去
                    }
                }
                res = Math.max(res, i - l + 1);//计算长度
            }
            return res;
        }

方法2:Map标记位置+滑动窗口

public int lengthOfLongestSubstringKDistinct(String s, int k) {
    int res = 0;
    Map<Character, Integer> map = new HashMap<>();//k:字符,v:该字符最近一次出现的位置
    int l = 0;//左窗口
    for (int i = 0; i < s.length(); i++) {
        map.put(s.charAt(i), i);//将当前字符和字符的位置关系记录下来
        while (map.size() > k) {//总的字符开始超过k个
            //如果 s[l]的 位置和l 不同,说明在[l+1 ... i ]之间又出现了字符s[l],这是不能移除s[l],反之则移除s[l]
            if (map.get(s.charAt(l)) == l) map.remove(s.charAt(l));
            ++l;
        }
        res = Math.max(res, i - l + 1);
    }
    return res;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值