424. Longest Repeating Character Replacement

Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.

Note:
Both the string's length and k will not exceed 104.

Example 1:

Input:
s = "ABAB", k = 2

Output:
4

Explanation:
Replace the two 'A's with two 'B's or vice versa.

 解题思路:记录下一个窗口大小里出现次数最大的字母mmax,如果mmax+k>=end-start+1说明当前的k是能够到达end的,这样窗口就会增大一格。否则将窗口平滑右移一格,但是窗口的大小不会变,也就是说窗口的大小只会增大不会减小。

class Solution {
public:
    int characterReplacement(string s, int k) {
        int count[128]={0};
        int mmax=0,start=0;
        for(int end=0;end<s.length();end++){
            mmax=max(mmax,++count[s[end]]);
            if(mmax+k<end-start+1)
                --count[s[start++]];
        }
        return s.length()-start;
    }
};

 

posted @ 2017-03-16 18:22  Tsunami_lj  阅读(119)  评论(0编辑  收藏  举报