题目链接
题目大意:给定一个合法的只包含小写字母和左右括号的括号序列 S,执行以下操作直到完成或失败:1,遇小写字母,则将其放入对应的盒子中,若盒子内已经有数了,则失败;2,遇 ‘(’,跳过;3,遇 ‘)’,则将与右括号匹配的左括号中间的所有字母都从盒子中拿出来。
解法:使用栈进行模拟就行了,只需要在模拟的时候新增一个 num[]数组 来记录每一个小写字母出现的次数即可,若出现的次数大于 1,则直接输出 -1。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<stack>
using namespace std;
const int N=3e5+5;
char s[N];
int num[N];
int main()
{
cin>>s+1;
int t=strlen(s+1);
stack<char> st;
for(int i=1;i<=t;i++){
if(s[i]=='(')st.push('(');
else if(s[i]==')'){
while(!st.empty()&&st.top()!='('){
int ch=st.top()-'a';
st.pop();
num[ch]--;
}
st.pop();
}else{
int ch=s[i]-'a';
st.push(s[i]);
num[ch]++;
if(num[ch]>1){
cout<<"No"<<endl;
return 0;
}
}
}
cout<<"Yes"<<endl;
return 0;
}