fork download
  1. import java.util.Stack;
  2.  
  3. class StackUsage {
  4.  
  5. public static void main(String[] args) {
  6. System.out.println(isBalanced("{[()]()}"));
  7. }
  8.  
  9. public static boolean isBalanced(String exp) {
  10. Stack<Character> st = new Stack<>();
  11.  
  12. for (int i = 0; i < exp.length(); i++) {
  13. char ch = exp.charAt(i);
  14.  
  15. if (ch == '(' || ch == '{' || ch == '[') {
  16. st.push(ch);
  17. } else if (ch == ')' || ch == '}' || ch == ']') {
  18. if (st.isEmpty()) {
  19. return false;
  20. }
  21.  
  22. char top = st.pop();
  23.  
  24. if (!match(top, ch)) {
  25. return false;
  26. }
  27. }
  28. }
  29.  
  30. return st.isEmpty();
  31. }
  32.  
  33. public static boolean match(char open, char close) {
  34. return (open == '(' && close == ')')
  35. || (open == '{' && close == '}')
  36. || (open == '[' && close == ']');
  37. }
  38. }
Success #stdin #stdout 0.08s 35216KB
stdin
Standard input is empty
stdout
true