P13414 [COCI 2012/2013 #4] ESEJ——又是一个栈——题解

· · 题解

如果你想要前往题目,请点击这里。

思路

这道题我们可以用一个栈来做。首先读入整个字符串,然后遍历这个字符串,如果栈空,直接压入当前字符;否则如果栈顶的字符与当前遍历到的字符不相同,把当前字符压入栈;否则,把栈顶的字符弹出。接着,如果栈空,答案变量 ans 就加一,这是一个好单词。最后,输出答案 ans。

AC code

#include<bits/stdc++.h>
using namespace std;
bool check(string s){
    stack<char> st;
    for(int i=0;i<s.size();i++){
        if(st.empty())st.push(s[i]);//栈空直接压入当前字符
        else if(st.top()!=s[i])st.push(s[i]);//栈顶的字符与当前遍历到的字符不相同,把当前字符压入栈
        else st.pop();//否则把栈顶的字符弹出
    }
    return st.empty();//判断栈空
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr),cout.tie(nullptr);
    int n,ans=0;
    cin>>n;
    while(n--){
        string s;
        cin>>s;
        if(check(s))ans++;//如果栈空,答案变量 ans 就加一,这是一个好单词
    }
    cout<<ans;
    return 0;
}