// TODO Choose the most appropriate data structure for the task and import it
import java.util.Stack;
// import java.util.Queue;
public class BalancedParenthesesChecker {
public static boolean isBalanced(String expression) {
boolean b = true;
Stack<Character> stack = new Stack<Character>();
char top;
char[] expr = expression.toCharArray();
for(char c: expr){
stack.push(c);
top = stack.peek();
if(c == '}' || c == ']'|| c == ')'){
stack.pop();
}
if(top == '{' || top == '[' || top == '('){
return true;
}
}
return false;
}
public static void main(String[] args) {
// TODO Test your implementation
String expression = "{(([a + b]) * c) - d}";
System.out.println("Is the expression balanced? " + isBalanced(expression));
expression = "([(a + b) * c)} - d";
System.out.println("Is the expression balanced? " + isBalanced(expression));
}
}
for referene here is my code. Right now, I am trying to do the balanced parentheses checker problem. I just learned stacks this week. I am unsure of how to get the logic correct for this problem entirely. The first one outputs that it is balanced, which is correct but also marks the second one as balanced which is incorrect. What should I keep in mind about the structure of stacks while writing this code to make the logic work?