南阳OJ-2-括号配对问题---栈的应用

题目链接:

http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=2

题目大意:

有一行括号序列,请你检查这行括号是否配对。

思路:

直接用栈来模拟

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cmath>
 6 #include<queue>
 7 #include<stack>
 8 #include<map>
 9 using namespace std;
10 typedef long long ll;
11 const int maxn = 1e6 + 10;
12 const int INF = 1 << 30;
13 int T, n, m;
14 int main()
15 {
16     cin >> T;
17     while(T--)
18     {
19         string s;
20         cin >> s;
21         bool ok = 1;
22         stack<char>q;
23         for(int i = 0; i < s.size(); i++)
24         {
25             if(s[i] == '[' || s[i] == '(')q.push(s[i]);
26             else
27             {
28                 if(q.empty())
29                 {
30                     ok = 0;
31                     break;
32                 }
33                 char c = q.top();
34                 //cout<<c<<endl;
35                 q.pop();
36                 if(s[i] == ']' && c != '[' || s[i] == ')' && c != '(')
37                 {
38                     ok = 0;
39                     break;
40                 }
41             }
42         }
43         if(ok)cout<<"Yes"<<endl;
44         else cout<<"No"<<endl;
45     }
46     return 0;
47 }
原文地址:https://www.cnblogs.com/fzl194/p/8699308.html