classSolution{publicintlengthOfLongestSubstringKDistinct(String s,int k){int left =0;int right =0;int len = s.length();int max =0;HashMap<Character,Integer> hashmap =newHashMap<Character,Integer>();while(right < len){
hashmap.put(s.charAt(right),right++);if(hashmap.size()== k +1){// delete the leftmost characterint del_idx =Collections.min(hashmap.values());
hashmap.remove(s.charAt(del_idx));// move left pointer of the slidewindow
left = del_idx +1;}
max =Math.max(max, right - left);}return max;}}
作者:user4006En
链接:https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters/solution/tu-jie-leetcodehua-dong-chuang-kou-by-us-x4ts/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
classSolution{public:intlengthOfLongestSubstringKDistinct(string s,int k){
unordered_map<char,int> mp;int res =0;int left =0;int n = s.size();for(int i =0; i < n; i ++){
mp[s[i]]= i;if(mp.size()> k){int new_left =remove_left(mp);
left = new_left;}
res =max(res, i - left +1);}return res;}intremove_left(unordered_map<char,int>&mp){int left_most = INT_MAX;
unordered_map<char,int>::iterator it0;for(auto it = mp.begin(); it != mp.end(); it ++){if(it->second < left_most){
left_most = it->second;
it0 = it;}}
mp.erase(it0);return left_most +1;}};