首页 > 试题广场 >

好串

[编程题]好串
  • 热度指数:8799 时间限制: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

备注:

s = input()
res = []
flag=True
for item in s:
    if item == "a":
        res.append(item)
    if item == "b":
        if len(res) == 0:              
            flag=False            
        else:
            res.pop()


if flag==True and len(res) == 0:
    print("Good")
else:
    print("Bad")

发表于 2025-08-06 21:17:19 回复(0)
#include <stdio.h>
#include <string.h>

#define MAX_LEN 1000005

int main() {
    char s[MAX_LEN];
    char stack[MAX_LEN];
    int top = 0;
    fgets(s, MAX_LEN, stdin);

    s[strcspn(s, "\n")] = '\0';
    int len = strlen(s);

    for (int i = 0; i < len; i++) {
        stack[top++] = s[i];
        if (top >= 2 && stack[top-2] == 'a' && stack[top-1] == 'b') {
            top -= 2;
        }
    }

    if (top == 0) {
        printf("Good\n");
    } else {
        printf("Bad\n");
    }

    return 0;
}
发表于 2026-01-20 19:44:16 回复(0)
感觉比括号匹配简单,用stack还是更符合题目的要求
#include <iostream>
using namespace std;
#include <stack>
#include <string>

bool isjudge(string& s){
    stack<char> st;
    if(s.empty()) return true;
    for(const auto& val : s){
        if(val == 'a') st.push(val);
        else if(val == 'b'){
            if(st.empty()) return false;
            else st.pop();
        }
    }
    return st.empty();
}

int main(){
    string s;
    cin >> s;
    cout << (isjudge(s) ? "Good" : "Bad") << endl;
    return 0;
}

发表于 2025-12-30 14:42:23 回复(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)
import sys

a, s = "", ""
for line in sys.stdin:
    a = line.split()
s = a[0]
while "ab" in s:
    s = s.replace("ab", "")
print("Good" if not s else "Bad")
发表于 2025-11-14 09:45:16 回复(0)

n = input().strip()

# 核心逻辑:不断删除 "ab" 子串,直到无法删除为止
while "ab" in n:
    n = n.replace("ab", "")  # 每次删除所有 "ab"(replace 会全局替换)

# 判断最终是否删空
if not n:
    print("Good")
else:
    print("Bad")

发表于 2025-08-14 13:44:38 回复(0)
import java.util.Scanner;
import java.util.Stack;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.next();

        boolean result = goodString(str);
        if (result) System.out.print("Good");
        else System.out.print("Bad");
    }

    public static boolean goodString(String str) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == 'a') stack.push(c);
            else if (c == 'b') {
                // 当 Stack 为空时调用 pop() 方法,不会返回任何值,而是会直接抛出空栈异常
                if (stack.isEmpty()) return false;
                if (stack.pop() == 'b') return false;
            }
        }
        return stack.isEmpty();
    }
}

发表于 2025-07-31 17:03:58 回复(0)
class Stock:
    def __init__(self) -> None:
        self.li = []

    def push(self, x):
        self.li.append(x)

    def pop(self):
        return self.li.pop()

    def query(self):
        return self.li[-1]

    def size(self):
        return len(self.li)
   
    def empty(self):
        return self.li == []

def smatch(s:str):
    stock = Stock()
    for i in s:
        if i == 'a':
            stock.push(i)
        elif i == 'b':
            if stock.empty():
                return 'Bad'
            stock.pop()
        else:
            pass
    if stock.empty():
        return 'Good'
    else:
        return 'Bad'

if __name__ == '__main__':
    s = input()
    print(smatch(s))
发表于 2025-07-19 16:36:31 回复(0)
#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)
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Deque<Character> stack = new ArrayDeque<>();
        String s = in.next();
        stack.push('1');//防止'b'先手,导致误判
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'a' ) {
                stack.push(s.charAt(i));
                continue;
            }
            if (s.charAt(i) == 'b' && !stack.isEmpty()) {
                char c = stack.pop();
                if (c != 'a') {
                    System.out.println("Bad");
                    return;
                }
                continue;
            }
        }
        stack.pop();//清除加入'1'带来的影响
        if (!stack.isEmpty())
            System.out.println("Bad");
        else System.out.println("Good");
    }
}
发表于 2026-02-02 19:53:31 回复(0)
#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;

int main() {
    string s;
    stack <char> temp;
    cin >> s;
    bool flag = true;
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == 'a') {
            temp.push(s[i]);
        }
        if (s[i] == 'b') {
            {
                if (temp.empty()) {
                    flag = false;
                    break;

                }
            }
            temp.pop();
        }
    }
    if (temp.empty() && flag == true) {
        cout << "Good" << endl;
    } else {
        cout << "Bad" << endl;
    }
    return 0;

}

发表于 2026-02-01 16:24:34 回复(0)
s = input()
lst = []
flag = 'Good'
for i in s:
    if i == 'a':
        lst.append(i)
    elif i == 'b':
        if lst != []:
            if lst[-1] == 'a':
                lst.pop(-1)
            else:
                flag = 'Bad'
        else:
            flag = 'Bad'
if lst != []:
    flag = 'Bad'
print(flag)
     

发表于 2026-01-30 21:24:57 回复(0)
stack = []
s = input()

for x in s:
    if x == 'a':  
        stack.append(x)
    elif x == 'b':  
        if not stack or stack[-1] != 'a':
            print("Bad")
            break
        stack.pop()  
    else:
        print("Bad")
        break
else:
    if not stack:  
        print("Good")
    else:  
        print("Bad")
发表于 2026-01-19 10:30:30 回复(0)
#include <iostream>
using namespace std;
#include<string>
#include<stack>
int main() {
    string s;
    cin>>s;
    stack<char>sta;
    for(int i=0;i<s.size();i++){
        if(s[i]=='a'){
            sta.push(s[i]);
        }
        else if(s[i]=='b'){
            if(sta.empty()){
                cout<<"Bad";
                return 0;
            }
            else{
                sta.pop();
            }
        }
    }
    if(sta.empty()){
        cout<<"Good";
        return 0;
    }
    else{
        cout<<"Bad";
        return 0;
    }
}
// 64 位输出请用 printf("%lld")

发表于 2025-11-19 20:10:36 回复(0)
s = list(input())
list_s = []
dict_s = {
    "b":"a"
}
for i in s:
    if i == "a":
        list_s.append(i)
    elif i in dict_s:
        if not list_s&nbs***bsp;list_s.pop() != dict_s[i]:
            print("Bad")
            break
else:
    if not list_s:
        print("Good")
    else:
        print("Bad")
        
    
和括号匹配方法一样
发表于 2025-11-19 15:21:35 回复(0)
#include<bits/stdc++.h>
using namespace  std;
int main(){
    stack<char> sta;
    string s;
    cin>>s;
    int len=s.size();
    if(len%2==1) {
        cout<<"Bad";
    }
    else{
        bool f=true;
        for(int i=0;i<s.size();i++){
            if(s[i]=='a'){
                sta.push(s[i]);
            }
            if(s[i]=='b'){
                if(sta.empty()){
                    f=false;
                    break;
                }
            else{
                char ch=sta.top();
                sta.pop();
                if(ch!='a'){
                    f=false;
                }
                 
                }
            }
        }
        if(f&&sta.empty()) cout<<"Good";
        else cout<<"Bad";
    }
    return 0;
}

发表于 2025-11-09 20:39:11 回复(0)
#include <stdbool.h>
#include <stdio.h>

bool isGoodString(char s[]){
    char stack[100001];
    int stack_used_len = 0;

    for (int i = 0; s[i] != '\0'; i++) {
        if(s[i] == 'a') stack[stack_used_len++] = 'a';
        else if( s[i] == 'b' && stack_used_len > 0){
            if(stack[stack_used_len-1] == 'a') stack_used_len--;
            else return false;
        }
        else return false;
    }

    if(stack_used_len) return false;

    return true;
}

int main() {
    char s[100001];
    scanf("%s", s);

    printf("%s", isGoodString(s)? "Good": "Bad");

    return 0;
}
#include <stdbool.h>
#include <stdio.h>

bool isGoodString(char s[]){
    char stack[100001];
    int stack_used_len = 0;

    for (int i = 0; s[i] != '\0'; i++) {
        if(s[i] == 'a') stack[stack_used_len++] = 'a';
        else if( s[i] == 'b' && stack_used_len > 0){
            if(stack[stack_used_len-1] == 'a') stack_used_len--;
            else return false;
        }
        else return false;
    }

    if(stack_used_len) return false;

    return true;
}

int main() {
    char s[100001];
    scanf("%s", s);

    printf("%s", isGoodString(s)? "Good": "Bad");

    return 0;
}

发表于 2025-11-05 11:51:04 回复(0)
for line in sys.stdin:
    s = line.strip()
    while "ab" in s:
        s = s.replace("ab","")
    print("Bad" if s else "Good")

发表于 2025-10-30 20:30:05 回复(0)
#include<bits/stdc++.h>
using namespace std;
int main(){
  stack<char> st;
  string s;
  int a,b;
  cin>>s;
  for( char c:s){
    if(c=='a'){
      st.push(c);
    }
    else if(c=='b') {
      if(!st.empty()&&st.top()=='a'){
        st.pop();
      }
      else {
        cout<<"Bad";
        return 0;
      }
    }
  }
 if(st.empty()){
  cout<<"Good";
 }else {
  cout<<"Bad";
 }
    return 0;
}
发表于 2025-09-13 14:17:04 回复(0)
s=input().strip()
g=[]
c1,c2=0,0

for i in range(len(s)):
    if s[i]=='a':
        g.append(s[i])
        c1+=1
    elif s[i]=='b':
        if not g:
            print('Bad')
            exit()
        top = g.pop()
        if(top == 'a' and s[i] == 'b'):
            c2+=1
if c1==c2:
    print('Good')
else:
    print('Bad')
发表于 2025-08-18 10:53:36 回复(0)

问题信息

上传者:牛客301599号
难度:
25条回答 1098浏览

热门推荐

通过挑战的用户

查看代码
好串