题目链接:http://www.lintcode.com/zh-cn/problem/longest-substring-with-at-most-k-distinct-characters/
给定一个字符串,找到最多有k个不同字符的最长子字符串。
您在真实的面试中是否遇到过这个题?
Yes
样例
例如,给定 s = "eceba" , k = 3,
T 是 "eceb",长度为 4.
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
if(k==0)
return 0;
int R=0,L=0,n=s.size();
map<char,int> m;
int maxp=0;
while(R<n){
++m[s[R]];
while(m.size()>k){
--m[s[L]];
if(m[s[L]]==0)
m.erase(m.find(s[L]));//删除值为零(相当于在区间[L,R]该字符并未出现)的元素,避免干扰m.size()
++L;
}
maxp=max(R-L+1,maxp);
++R;
}
return maxp;
}
};

本文介绍了一道关于寻找字符串中最长子串的问题,该子串包含最多k种不同的字符。通过滑动窗口和哈希映射的方法,实现了一个高效的解决方案。

475

被折叠的 条评论
为什么被折叠?



