瞪眼法可知,只要字符串符合存在一个a仅对应一个b,那这个字符串绝对可以通过插入ab得到。
采用栈,如果遇到a就入栈,遇到b则弹出栈顶,如果栈为空则说明匹配失败。(类似括号匹配)
#include <iostream>
#include <stack>
using namespace std;
int main() {
string s;
stack<char> st;
cin>>s;
for(auto c:s){
if(c=='a') st.push(c);
else if(c=='b'&&!st.empty()) st.pop();
else{
cout<<"Bad";
return 0;
}
}
if(st.empty()) cout<<"Good";
else cout<<"Bad";
}

京公网安备 11010502036488号