Uva-673 (Parentheses Balance)

Source: Internet
Author: User

Description

 
 

You are given a string consisting of parentheses () and []. A string of this type is said to be correct:

()
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
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;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.