题解 | 好串
好串
https://www.nowcoder.com/practice/9b072237ebdd4dd99562f01cbf594fac
这道题其实就是括号题的变种,用的还是栈的逻辑
#include <bits/stdc++.h>
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
stack<char> st;
string s;
cin>>s;
for(int i=0;i<s.size();i++){
// 开始遍历
// 若遍历到a,则进栈
if(s[i]=='a'){
st.push(s[i]);
}else{
// 遍历到b,先判断栈是否为空,为空则bad,若栈顶元素为a则让a出栈与b匹配
if(st.empty()){
cout<<"Bad";
return 0;
}else {
if(st.top()!='a')
{cout<<"Bad";
return 0;}
else st.pop();
}
}
}
// 遍历完最后,栈内元素必为空
if(st.empty()){
cout<<"Good";
}else {
cout<<"Bad";
}
return 0;
}


查看16道真题和解析