Sliding Window Summary -1 (Leetcode 424, Leetcode 340)

参考:http://www.cnblogs.com/grandyang/p/5999050.html

这两道题很像。都可以用Sliding Window来解。

Leetcode 424:

Longest Repeating Character Replacement 要求仅换K次,变成最长同样字符的continuous string,而optimal转换条件是

用string的长度 - 最多字符出现个数 (假设K没有限制)。由于K有限制,我们要用sliding window,来找到K可以实现的最大范围。注意,while中间那段更新max_cnt,没有也可以。

int characterReplacement(string s, int k) {
        if(s.empty()) return 0;
        unordered_map mp;
        int res = 0, max_cnt = 0;
        int start = 0;
        for(int i=0; i k){
                if(--mp[s[start]] == 0) mp.erase(s[start]);
                max_cnt = 0;
                for(auto it : mp){
                    if(it.second > max_cnt){
                        max_cnt = it.second;
                    }
                }
                start++;
            }
            res = max(res, i-start+1);
        }
        return res;
    }

Leetcode 340

int lengthOfLongestSubstringKDistinct(string s, int k) {
        if(s.empty()) return 0;
        unordered_map mp;
        int max_len = 0, start = 0;
        for(int i=0; i k){
                mp[s[start]]--;
                if(mp[s[start]] == 0){
                    mp.erase(s[start]);
                }
                start++;
            }
            max_len = max(max_len, i-start+1);
        }
        return max_len;
    }

你可能感兴趣的:(Sliding Window Summary -1 (Leetcode 424, Leetcode 340))