欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CodeForces - 960A:Check the string(思维)

程序员文章站 2022-06-02 22:17:04
...

题目
A has a string consisting of some number of lowercase English letters ‘a’. He gives it to his friend B who appends some number of letters ‘b’ to the end of this string. Since both A and B like the characters ‘a’ and ‘b’, they have made sure that at this point, at least one ‘a’ and one ‘b’ exist in the string.

B now gives this string to C and he appends some number of letters ‘c’ to the end of the string. However, since C is a good friend of A and B, the number of letters ‘c’ he appends is equal to the number of ‘a’ or to the number of ‘b’ in the string. It is also possible that the number of letters ‘c’ equals both to the number of letters ‘a’ and to the number of letters ‘b’ at the same time.

You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print “YES”, otherwise print “NO” (without the quotes).

输入
The first and only line consists of a string S (1≤|S|≤5000). It is guaranteed that the string will only consist of the lowercase English letters ‘a’, ‘b’, ‘c’.

输出
Print “YES” or “NO”, according to the condition.

题意
给你一个字符串,判断它是否满足一下条件:
1.所有的 ‘a’ 字符都在 ‘b’ ,'c’字符前;
2.所有的 ‘b’ 字符都在 ‘c’ 字符前;
3.‘c’ 字符的数量需要等于 ‘a’ 或 ‘b’ 字符的数量;

如果全都满足就输出YES,否则输出NO

思路
一开始我还想着定义6个变量,分别记录a,b,c第一次出现的位置和出现的次数,最后脑子突然就开窍了。

其实只要当a出现的时候b,c的数量为0就代表a先出现了,否则就代表a不是位于b,c之前的。
b也是同理。

接下来是最坑的,它的样例里竟然还有字符串中没有a或者没有b的情况!!!
不说了,全是泪????!

伊丽莎白!

CodeForces - 960A:Check the string(思维)
代码

#include<bits/stdc++.h>
using namespace std;

int main()
{
    string ss;
    cin>>ss;
    int flag=1;
    int a=0,b=0,c=0;
    for(int i=0; i<ss.size(); i++)
    {
        if(ss[i]=='a')
        {
            if(b||c)
            {
                flag=0;
                break;
            }
            a++;
        }
        if(ss[i]=='b')
        {
            if(!a||c)
            {
                flag=0;
                break;
            }
            b++;
        }
        if(ss[i]=='c')
        {
            if(!a||!b)
            {
                flag=0;
                break;
            }
            c++;
        }
    }
    if(a==0||b==0)  //真的坑,也是我脑子的问题
        flag=0;
    if((c==a||c==b)&&flag)
        cout<<"YES"<<endl;
    else
        cout<<"NO"<<endl;
}

最近正在筹备着写一篇知识讲解类的博客,第一次,希望能够写好(☆▽☆)。

下次再见~~

CodeForces - 960A:Check the string(思维)