Skip to content

Latest commit

 

History

History
42 lines (32 loc) · 991 Bytes

Ex_1_3_04.md

File metadata and controls

42 lines (32 loc) · 991 Bytes
title date draft tags categories
Algorithm4 Java Solution 1.3.04
2019-07-04 05:47:10 +0800
false
JAVA
TECH
archives

1.3.04

Problem:

Write a stack client Parentheses that reads in a text stream from standard input and uses a stack to determine whether its parentheses are properly balanced. For ex- ample, your program should print true for [()]{}{[()()]()} and false for [(]).

Solution:

  public static boolean isParenthesesBalanced(String exp) {
    _VarySizedCapacityStack<String> stack = new _VarySizedCapacityStack<>();
    for (int i = 0; i < exp.length(); i++) {
      String p = exp.substring(i, i + 1);
      stack.push(p);
      if ((p.equals(")") && stack.peek().equals("("))
          || p.equals("]") && stack.peek().equals("[")
          || p.equals("}") && stack.peek().equals("{")) {
          stack.pop();
        } else {
          return false;
        }
    }
    return stack.isEmpty();
  }

Reference: