424. Longest Repeating Character Replacement

本文介绍了一种使用滑动窗口解决字符串问题的方法,旨在找到经过最多k次替换后能形成的最长相同字母子串。通过计数每个字符出现次数并调整窗口大小来优化解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Description

Given an string only containing uppercase English letters, and an integer k, which represents you can replace any letter in the string 

with another letter at most k times. Find the longest substring consists of same letters.

 

2. Solution

Slide Window.

What is sure is that the answer is at least k+1.

First, use a map to count the number of the first k+1 letters in the string.

Then, enter a loop, the loop start at the k+1 position in the string.

In one loop, add up the current letter to the map, and find whether the diff between the numbers of letters in the range and the numbers of the most common letter in the map

is less or equal to k.

If it's true, update the answer to the maximum of the original answer and  the numbers of letters in the range.

Otherwise, move the left point to the right, until the range can be changed into string with same letters with at most k replacement.


3. Code

    int characterReplacement(string s, int k) {
        int n = s.size();
        if(n<=k+1) return n;
        map<char,int>m;
        for(int i=0;i<k+1;i++){
            m[s[i]]++;
        }
        int ans = k+1;
        int left = 0;
        for(int i=k+1;i<n;i++){
            m[s[i]]++;
            if(ok(m,k))
                ans = max(ans,i-left+1);
            else{
                while(!ok(m,k)){
                    m[s[left]]--;
                    left++;
                }
                ans = max(ans,i-left+1);
            }
        }
        return ans;
    }
    bool ok(map<char,int>m,int k){
        int big = 0;
        int sum = 0;
        for(int i=0;i<26;i++){
            sum+=m[i+'A'];
            big = max(big,m[i+'A']);
        }
        int diff = sum-big;
        if(diff<=k) return true;
        else return false;
        
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值