括号匹配

Posted by Cww97 on 2016-03-14

版权声明:本文为博主原创文章,未经博主允许不得转载。原文所在http://blog.csdn.net/cww97 https://blog.csdn.net/cww97/article/details/50887851

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<map>
#include<stack>
#include<string>
#include<cstdio>
#include<iostream>
using namespace std;
int a[1000];

bool check(string st){
map<char,int>mp;
mp['(']=0;mp[')']=1;
mp['[']=2;mp[']']=3;
mp['{']=4;mp['}']=5;
int A=0;
for (int i=0;i<st.size();i++){
if (st[i]!='('&&st[i]!=')'&&
st[i]!='['&&st[i]!=']'&&
st[i]!='{'&&st[i]!='}')continue;
a[++A]=mp[st[i]];
}

stack<int>s;
while (!s.empty())s.pop();
for (int i=1;i<=A;i++){
if (!(a[i]&1))s.push(a[i]);
else {
if (s.empty())return 0;
int x=s.top(); s.pop();
if (x^a[i]!=1)return 0;
}
}
return s.empty();
}
//=======cww=2016.2.29=9:12=========
int main(){
string st;
while (cin>>st){
if (check(st))puts("yes");
else puts("no");
}
return 0;
}