/*
Source: uva 673 ParenthesesBalance
Category: Stack
Abstract: check a bunch of strings of brackets, whether they are matched
Sample Input:
3
([])
(([()])))
([()[]()])()
Sample Output:
Yes
No
Yes
Idea: use stack
for every new bracket, check
if it is matched with the topof the stack, then pop stack
else put it in the stack
at the end, if the stack is empty, then the string is matched
other wise it is not.
Notice:
1. use -1 and -2 for ) and ]
use 1 and 2 for ( and [
if the sum of two brackets is 0, then they are matched
2. only check the sum is not enough
have to check the left bracket on the left, right on the right
(1) If the current bracket is right bracket,
if it matched with the top ofthe stack, pop the stack
If the current bracket is left,put it into the stack
(2) If the current bracket is right bracket and matched with the
top of the stack, pop stack
Otherwise, put it into the stack
3. For there may be empty string, so cannot use scanf(), if will
not recognise the empty string, so use gets()
*/
You are given a stringconsisting 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 thattakes a sequence of strings of this type and check their correctness. Yourprogram can assume that the maximum string length is 128.
Thefile contains a positive integer n and a sequence of n stringsof parentheses () and [], one string a line.
Asequence of Yes or No on the output file.
3
([])
(([()])))
([()[]()])()
Yes
No
Yes
MiguelRevilla
2000-08-14
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXL 200
int s[MAXL],top,ns;
int n;
char os[MAXL],ch[300];
void put_s(int x)
{
top++;
s[top]=x;
}
void pop_s()
{
top--;
}
int main()
{
ch['(']=1;
ch[')']=-1;
ch['[']=2;
ch[']']=-2;
scanf("%d",&n);
getchar();
for(int i=1;i<=n;i++)
{
top=-1;// stack is empty;
gets(os);
int len=strlen(os);
if (len==0)
{
printf("Yes\n");
continue;
}
for(int j=0;j<len;j++)
{
ns=ch[os[j]];
if (top==-1)
{
put_s(ns);
continue;
}
if ((ns<0)&&(ns+s[top]==0))
pop_s();
else put_s(ns);
}
if (top==-1)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
Method 2:
if (ns>0)
put_s(ns);
else
if (ns+s[top]==0)
pop_s();