why is it not accepting testcases
π‘ Balanced Parenthesis
Hey @17manishms
Youβre writing the code for only β(β , β)β brackets, the input string can consist of β[β, β]β, β{β, β}β also. So consider these as well in your code.
Also donβt print your final ans in between the for loop, this can print yes/ no multiple times. for example in ()), it will print NoYes in this case as your ans.
So a good way to handle this is maintaining a bool ans variable, and updating it whenever you get the ans as true or false, and printing the final ans as yes or no at the end.
#include
#include
#include
using namespace std;
int main() {
string str;
bool ans=true;
stack s;
getline(cin,str);
int i=0;
while(str.length()>i)
{
if(str[i]==β(β||str[i]==β{β||str[i]==β[β)
{
s.push(str[i]);
}
else if(str[i]==β)β|| str[i]==β}β||str[i]==β]β)
{
if(s.empty())
{
ans=false;
}
else{
s.pop();
}
}
i++;
}
if(s.empty() && ans)
{
cout<<βYesβ;
}
else{
cout<<βNoβ;
}
return 0;
}
again it is not accepting all the testcases
else if(str[i]==β)β|| str[i]==β}β||str[i]==β]β)
{
if(s.empty())
{
ans=false;
}
else{
s.pop();
}
}
The above part of your code is wrong. β(β will be popped only by β)β. β{β by β}β only and β[β by β]β. so you need to write separate cases for β)β, β}β and β]β. like:-
else if(str[i]==β)β)
{
if(s.empty())
{
ans=false;
}
else if(str[i] == β(β){
s.pop();
}
else{
ans = false;
}
}
similarly you need to write for } and ].
I hope Iβve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.