Given a string, find the length of the longest substring T that contains at most k distinct characters.
Example 1:
Input: s = "eceba", k = 2 Output: 3 Explanation: T is "ece" which its length is 3.
Example 2:
Input: s = "aa", k = 1 Output: 2 Explanation: T is "aa" which its length is 2.
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
vector<pair<char, int>> temp;
int ans = 0;
if (s.size() == 0 || k == 0) {
return ans;
}
if (s.size() == 1) {
return 1;
}
int count = 1;
for (int i = 1; i < s.size(); i++) {
if (s[i] == s[i - 1] ) {
count++;
} else {
temp.push_back(make_pair(s[i-1], count));
count = 1;
}
}
temp.push_back(make_pair(s[s.size() - 1], count));
int start = 0, end = 0;
int kSum = 0;
map<char, int> mp;
while (end < temp.size()) {
mp[temp[end].first] += temp[end].second;
kSum += temp[end].second;
while (mp.size() > k) {
mp[temp[start].first] -= temp[start].second;
kSum -= temp[start].second;
if (mp[temp[start].first] == 0) {
mp.erase(temp[start].first);
}
start++;
}
ans = max(ans, kSum);
end++;
}
return ans;
}
};
============== Efficient one ======
int lengthOfLongestSubstringKDistinct(string s, int k) { int res = 0, left = 0; unordered_map<char, int> m; for (int i = 0; i < s.size(); ++i) { ++m[s[i]]; while (m.size() > k) { if (--m[s[left]] == 0) m.erase(s[left]); ++left; } res = max(res, i - left + 1); } return res; }
No comments:
Post a Comment