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
這個題的意思是看一個表達示的括號是不是平衡的,空表達示也是平衡的,平衡就輸出YES,否則輸出NO。自己寫完過了,細節沒優化。
#include<iostream>
#include<stack>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
int main() {
string op;
stack<char> sp;
int n;
cin>>n;
getchar();//吃掉輸入數字後的回車
while(n--) {
int flag=1;
while(!sp.empty()) sp.pop();
getline(cin,op);
for(int i=0; i<op.size(); i++) {
if(op[i]=='('||op[i]=='[') sp.push(op[i]);
else {
if(op[i]==')') {
if(sp.empty()) sp.push(op[i]);
if(sp.top()!='(') {
cout<<"No"<<endl;
flag=0;
break;
} else {
sp.pop();
}
} else if(op[i]==']') {
if(sp.empty()) sp.push(op[i]);
if(sp.top()!='[') {
cout<<"No"<<endl;
flag=0;
break;
} else {
sp.pop();
}
}
}
}
if(sp.size()==0) cout<<"Yes"<<endl;
else if(flag&&sp.size()) cout<<"No"<<endl;
}
return 0;
}