Reputation: 67
below i have uploaded a code to check if there parentheses in a string are balanced or not using stacks.It is working for 1 input,but for multiple testcases the correct output is not working.PLEASE HELP.THANKS IN ADVANCE.
int main()
{
int t;
cin >>t;
cin.ignore();
while(t--)
{
{
stack s;
char *st;
st=new char[100];
gets(st);
s.create(strlen(st));
if(!count_elem(st))//counts if the brackets are in pairs or not
cout << "NO" <<endl;
else
func1(s,st);
}
}
return 0;
}
void func1(stack s,char *st)
{
static int i=0,flag=0;
// printf("%d %d\n",i,flag);
if(st[i]=='(' || st[i]=='{' || st[i]=='[')
{
flag=1;
s.push(st[i]);
}
else
{
if(s.isEmpty())
flag=0;
else
{
if(st[i]=='}')
{
//printf("%c\n",s.get_top());
if(s.get_top()=='{')
{
flag=1;
s.pop();
}
else
flag=0;
}
if(st[i]==')')
{
//printf("%c\n",s.get_top());
if(s.get_top()=='(')
{
flag=1;
s.pop();
}
else
flag=0;
}
if (st[i]==']')
{
//printf("%c\n",s.get_top());
if(s.get_top()=='[')
{
flag=1;
s.pop();
}
else
flag=0;
}
}
}
i++;
if(flag==1)
{
if(i<strlen(st))
func1(s,st);
else
cout << "YES"<<endl;
}
else
cout << "NO"<< endl;
}
Upvotes: 0
Views: 50
Reputation: 67
The problem is...when the program goes from one testcase to another,it does not reinitialize i=0,flag=0...because they have been declared as static variables.What can be done instead is....declare i,flag globally....and assign i=0;flag=0; just before making the first func()call for every testcase....
int main()
{
int t;
cin >>t;
cin.ignore();
while(t--)
{
{
stack s;
char *st;
st=new char[100];
gets(st);
s.create(strlen(st));
if(!count_elem(st))
cout << "NO" <<endl;
else
{
i=0;
flag=0;
func1(s,st);
}
delete []st;
}
}
return 0;
}
Upvotes: 0