首页 > 代码库 > UVa673 Parentheses Balance (栈)

UVa673 Parentheses Balance (栈)

链接:http://acm.hust.edu.cn/vjudge/problem/19102
分析:特别要注意空串情况,还有括号奇数个肯定不合法都可以特判。

 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <stack> 5 using namespace std; 6  7 int main() { 8     int n; 9     cin >> n; getchar();10     while (n--) {11         string line;12         getline(cin, line);13         if (line.compare("\n") == 0) {14             printf("Yes"); continue;15         }16         if (line.size() % 2) {17             printf("No\n"); continue;18         }19         stack<char> s;20         bool ok = true;21         for (int i = 0; i < line.size(); i++) {22             char ch = line[i];23             if (ch == () s.push(ch);24             else if (ch == [) s.push(ch);25             if (ch == ))26                 if (!s.empty() && s.top() == () s.pop();27                 else { ok = false; break; }28             else if (ch == ])29                 if (!s.empty() && s.top() == [) s.pop();30                 else { ok = false; break; }31         }32         if (ok && s.empty()) printf("Yes\n");33         else printf("No\n");34     }35     return 0;36 }

 

UVa673 Parentheses Balance (栈)