#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;
/*
Given a string, find the length of the longest substring T that contains at
most K distinct characters.
For example:
Given s = "eceba" and k = 2, T is "ece" which its length is 3.
*/
// using a queue to push the characters.
int longestSubstringWithKDistinct(string s, int k) {
if(s.size() <= k) return s.size();
int i = 0;
int maxSize = 0;
queue<char> chars;
unordered_map<char, int> hashMap;
while(i < s.size()) {
chars.push(s[i]);
hashMap[s[i]]++;
while(hashMap.size() > k) {
char ch = chars.front();
chars.pop();
hashMap[ch]--;
if(hashMap[ch] == 0) hashMap.erase(ch);
}
maxSize = max(maxSize, (int)chars.size());
i++;
}
return maxSize;
}
// two pointers.
int longestSubStringK(string s, int k) {
if(s.size() <= k) return s.size();
vector<int> hashMap(256, 0);
int maxSize = 0;
int count = 0;
int i = 0;
int j = 0;
while(i < s.size()) {
if(hashMap[s[i]] == 0) {
hashMap[s[i]]++;
count++;
} else {hashMap[s[i]]++;}
if(count > k) {
maxSize = max(maxSize, i - j);
while(--hashMap[s[j++]] > 0) {
}
count--;
}
i++;
}
maxSize = max(maxSize, i - j);
return maxSize;
}
int main(void) {
cout << longestSubstringWithKDistinct("ecebaddde", 2) << endl;
cout << longestSubStringK("ecebaddde", 2) << endl;
}
LeetCode 340. Longest Substring with At Most K Distinct Characters
最新推荐文章于 2023-04-14 19:10:16 发布
本文介绍了一种算法,该算法通过两种方法找到给定字符串中最长的包含最多K种不同字符的子串。这两种方法分别是使用队列和哈希表的方法,以及双指针技巧。文章提供了完整的代码实现,并通过示例进行说明。

712

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



