首页 > 试题广场 >

好串

[编程题]好串
  • 热度指数:8847 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
\hspace{15pt}牛牛喜欢跟字符串玩耍,他学会了一种新操作:在当前字符串中任意位置(包括开头和结尾)插入子串 \texttt{ab}

\hspace{15pt}牛牛称一个字符串为 好串,当且仅当它可以通过若干次上述操作从 空串 生成。

\hspace{15pt}例如,\texttt{ab}\texttt{aabb}\texttt{aababb} 都是好串,而 \texttt{aab}\texttt{ba}\texttt{abbb} 不是好串。

\hspace{15pt}现给定一个字符串 s,请判断字符串 s 是否是好串。

输入描述:
\hspace{15pt}在一行中输入一个仅由小写字母组成字符串 s1 \leqq |s| \leqq 10^5)。


输出描述:
\hspace{15pt}如果字符串 s 是好串,输出 \texttt{Good};否则输出 \texttt{Bad}
示例1

输入

ab

输出

Good

说明

初始空串,插入一次 "ab" 即可得到 "ab"。
示例2

输入

aab

输出

Bad

说明

无法通过插入 "ab" 操作得到 "aab"。
示例3

输入

abaababababbaabbaaaabaababaabbabaaabbbbbbbb

输出

Bad

备注:

#include <stdio.h>

int main() {
    char s[10001];
    int top=0; 
    scanf("%s",s);
    for (int i=0; s[i]!='\n' && s[i]!='\0'; i++) {
        char c = s[i]; 
        if (top<0) {
            printf("Bad");
            return 0;
        }
        if (c=='a') {
            top++;
        }

        if (c=='b') {
            top--;
        }
    }
    if (top!=0) {
        printf("Bad");
        return 0;
    }
    printf("Good");
    return 0;
}

发表于 2026-03-03 11:56:06 回复(0)
#include <stdio.h>
#include <stdbool.h>

int main() {
    int s;
    char stack[100000];
    int top =-1;
    bool hefa=true;
while ((s=getchar())!=EOF) {
    switch(s){
        case 'a':
        stack[++top]=s;
        break;
        case 'b':
        if(top==-1||stack[top]!='a'){
            hefa=false;
        }
        else {
        top--;
        }

    }
}
if(hefa&&top==-1){
    printf("Good");
}else {
    printf("Bad");
}
    return 0;
}
发表于 2025-11-22 16:35:27 回复(0)

问题信息

上传者:牛客301599号
难度:
2条回答 1103浏览

热门推荐

通过挑战的用户

查看代码
好串