UVA 673 栈 括号匹配
| Parentheses Balance |
You are given a string consisting of parentheses () and []. A string of this type is said to be correct:
- (a)
- if it is the empty string
- (b)
- if A and B are correct, AB is correct,
- (c)
- if A is correct, (A) and [A] is correct.
Write a program that takes a sequence of strings of this type and check their correctness. Your program can assume that the maximum string length is 128.
Input
The file contains a positive integer n and a sequence of n strings of parentheses () and [], one string a line.
Output
A sequence of Yes or No on the output file.
Sample Input
3 ([]) (([()]))) ([()[]()])()
Sample Output
Yes No Yes
题目大意和分析:
括号匹配。从头遍历。若输入的是“(”,“[”。将他们放入栈中。如果是“)”,或“]”。则判断栈是否为空。不为空。则看栈顶的元素。如果是“(”或“[”。则将栈顶元素弹出。
否则将tmp 置为 1.最后判断栈是否为空,为空切他们tmp = 0,则输出Yes。反之输出No。
这是一道栈的经典题,但也是一道水题,进栈出栈就如此简单的操作,无复杂算法。
题目链接:http://acm.uva.es/local/online_judge/search_uva.html
AC代码:
#include <iostream> #include <string> #include <cstring> #include <cstdio> #include <stack> #include <vector> using namespace std; const int MAX=128+1; int n,len; string str;//读入 int main() { cin >> n; cin.get ( );//控制回车 while ( n-- ) { bool tmp = 0; stack < char > sta;//创建一个栈 getline ( cin, str );//将读到的放入str中 int len = str.length ( ); for ( int i = 0; i < len; ++i ) { if ( str[i] == '(' || str[i] == '[' ) sta.push( str[i] ); else if ( str[i] == ')' && !sta.empty( ) && sta.top ( ) == '(' ) sta.pop ( ); else if ( !sta.empty ( ) && str[i] == ']' && sta.top ( ) == '[' ) sta.pop ( ); else tmp = 1; } if(tmp==0 && sta.empty()) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }
浙公网安备 33010602011771号