Balance string

Topic: A string s of length n, which contains only the four characters 'Q', 'W', 'E', 'R'.
If the number of occurrences of the four characters in the character string is n / 4, it is a balanced character string.
Now you can replace a continuous substring in s with an arbitrary string of the same length that contains only those four characters, making it a balanced string. What is the minimum length of the replacement substring?
If s is balanced, then output 0 .

Input: A
line of characters represents the given string s

Output:
An integer indicates the answer
. I will not give examples here.

Succession idea: General extreme value problems can be dichotomous, but this problem can be taken with a ruler, maintaining a continuous interval, and the time complexity is not high, it is linear.

Code:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int q,w,e,r,n;
int main()
{
    string a;
    q=w=e=r=0;
    cin>>a;
    n=a.size();
    for(int i=0;i<a.size();i++)//初始化
    {
        if(a[i]=='Q')q++;
        else if(a[i]=='W')w++;
        else if(a[i]=='E')e++;
        else r++;
    }
    if(q==n/4&&w==n/4&&e==n/4)cout<<0<<endl;//一开始就满足
    else
    {
        int ll=0,rr=0,ans=n+1;//尺取
        while(1)
        {
            int q1=0,w1=0,e1=0,r1=0;
            int q2=q,w2=w,e2=e,r2=r;
            for(int i=ll;i<=rr;i++)
            {
                if(a[i]=='Q')q1++;
                else if(a[i]=='W')w1++;
                else if(a[i]=='E')e1++;
                else r1++;
            }
            q2-=q1,w2-=w1,e2-=e1,r2-=r1;
            int h=max(max(q2,w2),max(e2,r2));
            int total=rr-ll+1-(4*h-q2-w2-e2-r2);//减去达到平均的最低要求
            if(total>=0&&total%4==0)//这里只要满足减去之后mod4=0即可            			    
            {
                ans=min(ans,rr-ll+1);//满足左区间右移
                ll++;
            }else//不满足右区间右移
            {
                rr++;
            }
            if(ans==1||rr==n)
            {
                break;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}
PGZ
Posted 34 original articles · liked 0 · visits 876

Guess you like

Origin blog.csdn.net/qq_43653717/article/details/104972999