#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
最新推荐文章于 2024-03-20 17:56:58 发布