[leetcode] 340. Longest Substring with At Most K Distinct Characters 解题报告

题目链接: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/

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

For example, Given s = “eceba” and k = 2,

T is "ece" which its length is 3.


思路: 用一个队列+一个hash表, 每次将一个字符加到队列里去, 并且在hash表中将其计数+1, 如果hash表的长度大于k了, 说明现在字符超出了个数, 因此我们将队列的首元素出队列, 并且在hash表中将对应的字符计数-1, 如果这个字符的计数=0了, 那么就在hash表中删除这个字符, 直到hash表的长度<=k. 并且每次和队列长度比较更新最大长度.

代码如下: 

class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        if(s.size() == 0 || k <= 0) return 0;
        unordered_map<char, int> mp;
        queue<char> que;
        int Max = 0;
        for(int i = 0; i< s.size(); i++)
        {
            que.push(s[i]);
            mp[s[i]]++;
            while(mp.size() > k)
            {
                char ch = que.front();
                que.pop();
                mp[ch]--;
                if(mp[ch] == 0)
                    mp.erase(ch);
            }
            Max = max(Max, (int)que.size());
        }
        return Max;
    }
};


你可能感兴趣的:(LeetCode,Queue,hash)