栈的应用——括号匹配

题目描述:编写程序,判定给定表达式中的括号是否匹配,表达式中的合法括号位 “(”,“)”,“[”,“]”,“{”,“}”,括号可按任意次序嵌套使用。

输入说明:有多个表达式,出入数据第一行是表达式的数目,每个表达式占一行。

输出说明:对每个表达式,若其括号匹配则输出“Yes”,否则输出“No”。

C++实现:

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
int main()
{
int n;
char ch[100];
stack<int>s;
bool flag = true;
cin >> n;
while (n--)
{
cin >> ch;
flag = true;
for (int i = 0; ch[i] != '\0'; i++)
{
if (ch[i] == '(' || ch[i] == '[' || ch[i] == '{')
{
s.push(ch[i]);
continue;
}
if (!s.empty())
{
if (ch[i] == ')'&&s.top() == '(')
{
s.pop();
continue;
}
if (ch[i] == ']'&&s.top() == '[')
{
s.pop();
continue;
}
if (ch[i] == '}'&&s.top() == '{')
{
s.pop();
continue;
}
if (ch[i] == ')'&&s.top() != '(')
{
flag = false;
break;
}
if (ch[i] == ']'&&s.top() != '[')
{
flag = false;
break;
}
if (ch[i] == '}'&&s.top() != '{')
{
flag = false;
break;
}
}
else {
if (ch[i] == ')' || ch[i] == ']' || ch[i] == '}')
{
flag = false;
break;
}
}
}
if (flag)
{
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
return 0;
}

/——测试用例——/
/
[(d+f)
{}]
[(2+3)]
()}
[4(6]7)9
*/

Author: wnxy
Link: https://wnxy.github.io/2020/03/27/Stack-application-bracket-matching/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.