Sicily-brackets matching

简要思路:利用栈存储括号(分小括号,中括号,大括号),如果是左括号就push进栈;如果是右括号且top是相应的左括号,就pop了。到最后遍历完整个字符串,如果这个栈是空的,说明所有的括号都匹配了。

下面上代码。

 1 #include <iostream>
 2 #include <cstring>
 3 #include <string>
 4 #include <stack>
 5 using namespace std;
 6 
 7 int main() {
 8     int T;
 9     cin >> T;
10     while(T--) {
11         int count = 0;
12         string str;
13         cin >> str;
14         int size = str.length();
15         stack<char> temp;
16         for (int i = 0; i < size; i++) {
17             if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
18                 temp.push(str[i]);
19             } else {
20                 if (str[i] == ')') {
21                     if (!temp.empty() && temp.top() == '(') {
22                         temp.pop();
23                     } else {
24                         cout << "No" << endl;
25                         count = 1;
26                         break;
27                     }
28                 }
29                 if (str[i] == '}') {
30                     if (!temp.empty() && temp.top() == '{') {
31                         temp.pop();
32                     } else {
33                         cout << "No" << endl;
34                         count = 1;
35                         break;
36                     }
37                 }
38                 if (str[i] == ']') {
39                     if (!temp.empty() && temp.top() == '[') {
40                         temp.pop();
41                     } else {
42                         cout << "No" << endl;
43                         count = 1;
44                         break;
45                     }
46                 }
47             }
48         }
49         if (count == 0) {
50             if (temp.empty() == true) {
51             cout << "Yes" << endl; 
52         } else {
53         cout << "No" << endl;
54     }
55         }
56         
57 }
58     return 0;
59 }

 

转载于:https://www.cnblogs.com/SYSU-Bango/p/6306962.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值