题解:P13414 [COCI 2012/2013 #4] ESEJ
Zjb_nhzx_2021 · · 题解
P13414 ESEJ 题解
题目大意
给出
Mirko 会在单词上方画弧,将成对的相同字母(
解题思路
本题就是 P1739 的进阶版,同样可以用栈来解决,下面是解题步骤:
- 检查单词长度是否为偶数。
- 循环遍历字符串,将栈顶字母与当前字母比较,如果相同则出栈(匹配上了),否则将当前字母字母入栈。
- 最后判断栈是否为空(有没有匹配完)。
AC Code
#include<bits/stdc++.h>
using namespace std;
int gw(string s) {
int n=s.size();
// 第一步:检查长度是否为偶数
if(n%2!=0){
return false;
}
stack<char>st;
//第二步:匹配每个字母
for(int i=0;i<s.size();i++){
if(!st.empty()&&st.top()==s[i])
st.pop(); //遇到相同字母出栈
else st.push(s[i]);
}
return st.empty();
}
int n,sum;
int main(){
scanf("%d",&n);
while(n--){
string w;
cin>>w;
sum+=gw(w);//统计“好单词”的个数
}
printf("%d",sum);
return 0;
}