please check my JAVA code. One of my test cases is wrong. The question is as stated in the image My answer: import java.util.*; public class BalanceSymbolChecker { public static void main(String[] args) { Scanner scn=new Scanner(System.in); Stack stack=new Stack(); String str=scn.nextLine(); // take input boolean ans=false; int flag=0; while(str.length()!=0) { char ch=str.charAt(0); str=str.substring(1); if(stack.isEmpty()&&(ch==')'||ch==']'||ch=='}'||ch=='>')) { flag=1; break; } else if(ch=='('||ch=='['||ch=='{'||ch=='<') { stack.push(ch); } else if(ch==')') { char top=(char) stack.peek(); if(top=='(') { stack.pop(); } } else if(ch==']') { char top=(char) stack.peek(); if(top=='[') { stack.pop(); } } else if(ch=='}') { char top=(char) stack.peek(); if(top=='{') { stack.pop(); } } else if(ch=='>') { char top=(char) stack.peek(); if(top=='<') { stack.pop(); } } } if(flag==1) { ans=false; } else { if(!stack.isEmpty()) { ans= false; //unbalanced } else { ans= true; //balanced } } if(ans==true) { System.out.println("Balanced"); } else { System.out.println("Unbalanced"); } } }
please check my JAVA code. One of my test cases is wrong.
The question is as stated in the image
My answer:
import java.util.*;
public class BalanceSymbolChecker {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
Stack<Character> stack=new Stack<Character>();
String str=scn.nextLine(); // take input
boolean ans=false;
int flag=0;
while(str.length()!=0) {
char ch=str.charAt(0);
str=str.substring(1);
if(stack.isEmpty()&&(ch==')'||ch==']'||ch=='}'||ch=='>')) {
flag=1;
break;
}
else if(ch=='('||ch=='['||ch=='{'||ch=='<') {
stack.push(ch);
}
else if(ch==')') {
char top=(char) stack.peek();
if(top=='(') {
stack.pop();
}
}
else if(ch==']') {
char top=(char) stack.peek();
if(top=='[') {
stack.pop();
}
}
else if(ch=='}') {
char top=(char) stack.peek();
if(top=='{') {
stack.pop();
}
}
else if(ch=='>') {
char top=(char) stack.peek();
if(top=='<') {
stack.pop();
}
}
}
if(flag==1) {
ans=false;
}
else {
if(!stack.isEmpty()) {
ans= false; //unbalanced
}
else {
ans= true; //balanced
}
}
if(ans==true) {
System.out.println("Balanced");
}
else {
System.out.println("Unbalanced");
}
}
}
Step by step
Solved in 3 steps with 3 images
Now the last test case is wrong. Can u help me