Description
You are given a string consisting of parentheses()And[]. A string of this type is said to beCorrect:
-
()
-
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 integerNAnd a sequenceNStrings of parentheses()And[], One string a line.
Output
A sequenceYesOrNoOn the output file.
Sample Input
3([])(([()])))([()[]()])()
Sample output
YesNoYes
This question is to see if the parentheses of an expression are balanced. The empty expression is also balanced. If the balance is achieved, yes is output; otherwise, no is output.
Solution:
1. If the expression is blank, the output is yes.
2. A stack is used to show that scanning is performed from left to right. When the left bracket is added to the stack, the right brace is output to the stack. If the last line is empty, yes is output. Otherwise, no is output.
#include <iostream>#include<deque>#include<algorithm>#include<cstdio>#include<stack>#include<string>using namespace std;char f(char c){ if(c==')')return '('; if(c==']')return '['; return 0;}bool judge(const string& s){ stack<char>st; st.push('0'); for(int i=0;i<s.size();i++) { if(st.top()!=f(s[i])) st.push(s[i]); else st.pop(); } return st.size()==1;}int main(){ int n; cin>>n; string s; getchar(); while(n--) { getline(cin,s); if(s.size()==0||judge(s))cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0;}