LintCode 1246: Longest Repeating Character Replacement (同向双指针好题)

1246 · Longest Repeating Character Replacement
Algorithms
Medium
Accepted Rate
45%
Description
Solution
Notes
Discuss
Leaderboard
Record

Description
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.

Both the string’s length and k will not exceed 10^4.

Example
Example1

Input:
“ABAB”
2
Output:
4
Explanation:
Replace the two 'A’s with two 'B’s or vice versa.
Example2

Input:
“AABABBA”
1
Output:
4
Explanation:
Replace the one ‘A’ in the middle with ‘B’ and form “AABBBBA”.
The substring “BBBB” has the longest repeating letters, which is 4.
Tags
Company
Pocket Gems

解法1:

class Solution {
public:
    /**
     * @param s: a string
     * @param k: a integer
     * @return: return a integer
     */
    int characterReplacement(string &s, int k) {
        int len = s.size();
        if (len == 0) return 0;
        if (k == 0) return 1;
        
        int i = 0, j = 0;
        vector<int> freq(26, 0);
        int maxLen = 1, maxFreq = 0;
        for (i = 0; i < len; ++i) {
            j = max(i, j);
            while (j < len && (j - i - maxFreq <= k)) {
                freq[s[j] - 'A']++;
                maxFreq = max(maxFreq, freq[s[j] - 'A']);
                j++;
            }
            
            if (j - i - maxFreq > k) maxLen = max(maxLen, j - i - 1);
            else {
                maxLen = max(maxLen, j - i);
            }
            freq[s[i] - 'A']--;
        }
        return maxLen;
    }
};

二刷:

class Solution {
public:
    /**
     * @param s: a string
     * @param k: a integer
     * @return: return a integer
     */
    int characterReplacement(string &s, int k) {
        int n = s.size();
        int left = 0, right = 0;
        int freq[26] = {0}, maxFreq = 0;
        int maxLen = 0;
        while (right < n) {
            char ch = s[right];
            int index = ch - 'A';
            freq[index]++;
            if (maxFreq < freq[index]) {
                maxFreq = max(maxFreq, freq[index]);
                //maxFreqIndex = index;
            }
            right++;
            //while (left < right && right - left - maxFreq > k) {
            while (right - left - maxFreq > k) { //注意:这里用if也对,因为满足right-left-maxFreq>k的情形就是因为right向右移动了一位,所以这里left最多也只需要往右移动一位即可。所以,如果用while的话,maxFreq不用改。
                char ch = s[left];
                int index = ch - 'A';
                freq[index]--;
                left++;
            }
            maxLen = max(maxLen, right - left);
        }
        return maxLen;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值