给定一个字符串,找到最多有k个不同字符的最长子字符串。
例如,给定 s = "eceba" , k
 = 3,
T 是 "eceb",长度为 4.
O(n), n 是所给字符串的长度
分析:采用双指针,用map记录双指针中间的字符串是否满足要求
代码:
class Solution {
public:
    /**
     * @param s : A string
     * @return : The length of the longest substring 
     *           that contains at most k distinct characters.
     */
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        // write your code here
        int ret = 0;
        int start = 0;
        int end = 0;
        map<char,int> m;
        for(int i=0;i<s.length();i++)
        {
            m[s[i]]++;
            end = i;
            while(m.size()>k)
            {
                m[s[start]]--;
                if(m[s[start]]==0)
                    m.erase(m.find(s[start]));
                start++;
            }
            ret = max(ret,end-start+1);
        }
        return ret;
    }
};
原文地址:http://blog.csdn.net/wangyuquanliuli/article/details/45725061