字符串括号匹配


给出一个字符串,判断其中的左右圆括号是否匹配,

注:需同时判断左右圆括号 () ,左右中括号 [],左右大括号 {}

不需要考虑括号之间的优先级的问题,也就是说,小括号包含大括号,也是被允许的

输入

一行一个字符串,以字符@为结尾

输出

若匹配,输出 YES,若不匹配,则输出 NO

样例

1
a(cc[])bbb()@ YES
1
a(cc[)]bbb()@ NO

代码

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
#include<iostream>
#include<string>
#include<stack>
using namespace std;

bool isValid(string str) {
stack<char> stack;
for (int i = 0; i < str.length(); ++i) {
switch (str[i]) {
case '(':
case '[':
case '{':
stack.push(str[i]);
break;
case ')':
if (stack.empty() || stack.top() != '(') return false;
stack.pop();
break;
case '}':
if (stack.empty() || stack.top() != '{') return false;
stack.pop();
break;
case ']':
if (stack.empty() || stack.top() != '[') return false;
stack.pop();
break;
}
}
return stack.empty();
}

int main() {
string str;
cin >> str;
if (isValid(str)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
return 0;
}