title | date | draft | tags | categories | |||
---|---|---|---|---|---|---|---|
Algorithm4 Java Solution 1.3.04 |
2019-07-04 05:47:10 +0800 |
false |
|
|
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 [(])
.
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();
}