386. 最多有k个不同字符的最长子字符串

 

https://www.lintcode.com/problem/longest-substring-with-at-most-k-distinct-characters/description

leetcode 340

给定字符串S,找到最多有k个不同字符的最长子串T

样例

样例 1:

输入: S = "eceba" 并且 k = 3
输出: 4
解释: T = "eceb"

样例 2:

输入: S = "WORLD" 并且 k = 4
输出: 4
解释: T = "WORL" 或 "ORLD"
class Solution {
public:
    /**
     * @param s: A string
     * @param k: An integer
     * @return: An integer
     */
    int lengthOfLongestSubstringKDistinct(string &s, int k) {
        // write your code here
        int res=0;
        int start=0;
        int end=0;
        map m;
        for(int i=0;ik){
                m[s[start]]--;
                if(m[s[start]]==0){
                    m.erase(m.find(s[start]));
                }
                start++;
            }
            res=max(res,end-start+1);
        }
        return res;
    }
};

 

你可能感兴趣的:(lintcode,string)