UVa 673 平衡的括号

题意:给出包含"()"和"[]"的括号序列,判断是否合法。

用栈来完成,注意空串就行。

 1 #include<iostream>
 2 #include<string>
 3 #include<cstring>
 4 #include<stack>
 5 using namespace std;
 6 
 7 stack<char> sta;
 8 string s;
 9 
10 int solve()
11 {
12     char str;
13     if (s[0] == ' ')   return 1;
14     else
15     {
16         int l = s.length();
17         for (int i = 0; i < l; i++)
18         {
19             if (s[i] == '(' || s[i] == '[')
20             {
21                 sta.push(s[i]);
22             }
23             else if (s[i] == ')')
24             {
25                 str = ' ';
26                 while (str != '(')
27                 {
28                     if (!sta.empty())
29                     {
30                         str = sta.top();
31                         sta.pop();
32                     }
33                     else  return 0;
34                 }
35             }
36             else if (s[i] == ']')
37             {
38                 str = ' ';
39                 while (str != '[')
40                 {
41                     if (!sta.empty())
42                     {
43                         str = sta.top();
44                         sta.pop();
45                     }
46                     else  return 0;
47                 }
48             }
49         }
50     }
51     if(!sta.empty()) return 0;
52     else return 1;
53 }
54 
55 int main()
56 {
57     int t;
58     cin >> t;
59     getchar();
60     while (t--)
61     {
62         while (!sta.empty())  sta.pop();
63         getline(cin, s);
64         int ans=solve();
65         if (ans)  cout << "Yes" << endl;
66         else cout << "No" << endl;
67     }
68     return 0;
69 }
原文地址:https://www.cnblogs.com/zyb993963526/p/6239266.html