Solution of 673 - Parentheses Balance

Problem Description
source:https://uva.onlinejudge.org/external/6/673.html

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 


([]) 
(([()]))) 
([()[]()])() 

Sample Output 

Yes 
No 
Yes

Solution:
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include<stack>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
    int i, test, j, len;
        char expression[150];
        scanf("%d\n", &test);
        for(i=1;i<=test;i++)
        {
            stack<char> mystack;
            cin.getline(expression,150);
            len=strlen(expression);
            if(len==0)
            {
                printf("Yes\n");
                continue;
            }
            for(j=0; j<len; j++)
            {
                if(expression[j]=='(' || expression[j]=='[')
                    mystack.push(expression[j]);
                else if (!mystack.empty() && ((mystack.top()=='(') &&(expression[j]==')' ) || (mystack.top()=='[') &&expression[j]==']' ))
                        mystack.pop();
                else if(expression[j]==' ')
                    continue;
                else
                        break;

            }

             if(mystack.empty() && len==j)
                printf("Yes\n");
            else
                printf("No\n");

        }
    return 0;
}
image

No comments:

Post a Comment

Write your comment - Share Knowledge and Experience