2022-3-31 Leetcode 340.至多包含K个不同字符的最长字串

在这里插入图片描述

class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        int left = 0;
        int right = 0;
        int len = s.length();
        int max = 0;
        HashMap<Character, Integer> hashmap = new HashMap<Character, Integer>();
        while(right < len){
            hashmap.put(s.charAt(right),right++);

            if (hashmap.size() == k + 1) {
                // delete the leftmost character
                int del_idx = Collections.min(hashmap.values());
                hashmap.remove(s.charAt(del_idx));
                // move left pointer of the slidewindow
                left = del_idx + 1;
            }
            max = Math.max(max, right - left);
        }

        return max;
    }
}

作者:user4006En
链接:https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters/solution/tu-jie-leetcodehua-dong-chuang-kou-by-us-x4ts/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        unordered_map<char, int> mp;
        int res = 0;
        int left = 0;
        int n = s.size();
        for (int i = 0; i < n; i ++) {
            mp[s[i]] = i;
            if (mp.size() > k) {
                int new_left = remove_left(mp);
                left = new_left;
            }
            res = max(res, i - left + 1);
        }
        return res;
    }

    int remove_left(unordered_map<char, int> &mp) {
        int left_most = INT_MAX;
        unordered_map<char, int>::iterator it0;
        for (auto it = mp.begin(); it != mp.end(); it ++) {
            if (it->second < left_most) {
                left_most = it->second;
                it0 = it;
            }
        }
        mp.erase(it0);
        return left_most + 1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值