1.question:

find the longest length in the string has k types of characters

2.code attention

a.length calculate need plus 1 

i-left+1

b.if one character not in the unordered_map,need to erase it

if(hash[s[left]==0] hash.erase(s[left]);

c.use while can solve all problems ,needn't use if else if

code part:

class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        unordered_map<char, int> hash;
        int left = 0, Max = 0;
        for(int i =0; i < s.size(); i++)
        {
            hash[s[i]]++;
            while(hash.size()>k)
            {
                hash[s[left]]--;
                if(hash[s[left]]==0) hash.erase(s[left]);
                left++;
            }
            Max = max(Max, i-left+1);
        }
        return Max;
    }
};

 

posted on 2020-10-28 09:28  黑暗尽头的超音速炬火  阅读(70)  评论(0编辑  收藏  举报