美文网首页
leetcode 340+159

leetcode 340+159

作者: Ariana不会哭 | 来源:发表于2019-01-11 06:55 被阅读0次

-code:

int lengthOfLongestSubstringKDistinct(string s, int k) {
        unordered_map<char, int> map;
        int ans = 0;
        int start = 0;
        for (int i = 0; i < s.size(); i++) {
            map[s[i]]++;
            while (map.size() > k) {
                if (--map[s[start]] == 0)
                    map.erase(s[start]);
                start++;
            }
            ans = max(ans, i - start + 1);
        }
        return ans;
    }

    int lengthOfLongestSubstringKDistinct(string s, int k) {
        unordered_map<char, int> map;
        int left = 0, right = 0;
        int count = 0;
        int ans = 0;
        for (right = 0; right < s.length(); right++) {
            if (map[s[right]]++ == 0)
                count++;
            while (count > k) {
                if (map[s[left++]]-- == 1)
                    count--;
            }
            ans = max(ans, right - left + 1);
        }
        return ans;
    }

相关文章

网友评论

      本文标题:leetcode 340+159

      本文链接:https://www.haomeiwen.com/subject/frrtdqtx.html