LintCode 386. 最多有k个不同字符的最长子字符串
题目描述
给定字符串S,找到最多有k个不同字符的最长子串T。
样例
样例 1:
输入: S = "eceba" 并且 k = 3
输出: 4
解释: T = "eceb"
样例 2:
输入: S = "WORLD" 并且 k = 4
输出: 4
解释: T = "WORL" 或 "ORLD"
挑战
O(n) 时间复杂度
解题思路
双指针
参考代码
class Solution {
public:
/**
* @param s: A string
* @param k: An integer
* @return: An integer
*/
int lengthOfLongestSubstringKDistinct(string &s, int k) {
// write your code here
if (s.empty() || s.size() == 0 || k <= 0) return 0;
int j = 0;
int maxLength = 0;
unordered_map<char,int> hash;
for (int i = 0; i < s.length(); i++) {
while (j < s.length() && hash.size() <= k) {
if (hash.size() == k && hash.find(s[j]) == hash.end()) {
break;
}
hash[s[j]]++;
j++;
}
maxLength = max(maxLength, j - i);
int currentCount = hash[s[i]] - 1;
if (currentCount == 0) {
hash.erase(s[i]);
} else {
hash[s[i]] = currentCount;
}
}
return maxLength;
}
};