给定一个字符串 s ,找出 至多 包含 k 个不同字符的最长子串 T。
示例 1:
输入: s = "eceba", k = 2
输出: 3
解释: 则 T 为 "ece",所以长度为 3。
示例 2:
输入: s = "aa", k = 1
输出: 2
解释: 则 T 为 "aa",所以长度为 2。
提示:
1 <= s.length <= 5 * 104
0 <= k <= 50
通过次数12,592提交次数25,447
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目分析
当然双指针啦
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
int book[128]{0};
int i =0,j = -1,cnt = 0,n = s.size(),maxlenth = 0;
if (k == 0)return 0;
while(j<n){
if(cnt<=k){
maxlenth = max(maxlenth,j-i+1);
j++;
if(book[s[j]]++ == 0)cnt++;
continue;
}
if(--book[s[i]] == 0)cnt--;
i++;
}
return maxlenth;
}
};
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
unordered_map<char,int> map;
if(k==0){return 0;}
int n = s.size();
int ans =0;
for(int l=0,r=0;r<n;r++){
map[s[r]]++;
while(map.size()>k){
map[s[l]]--;
if(map[s[l]]==0){map.erase(s[l]);}
l++;
}
ans = max(ans,r-l+1);
}
return ans;
}
};
总结
第二段代码是评论区前辈的。
用上了unordered_map的性质,比较新奇,我不知道,另外他的滑动窗口写法也与我不同,值得学习。
但是我不喜欢他这道题用unordered_map,任何降低代码运行速度、空间利用率和可读性的操作都是不应该的。