这题需要注意:
public class Solution { private static final Stack<Character> stack = new Stack<Character>(); public boolean isValid(String s) { stack.clear(); for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (!isLeft(c)) { if (stack.isEmpty()) { return false; } if (!isPair(stack.pop(), c)) { return false; } } else { stack.push(c); } } return stack.isEmpty(); } private boolean isLeft(char c) { return c == ‘(‘ || c == ‘[‘ || c == ‘{‘; } private boolean isPair(char left, char right) { if (left == ‘(‘) { return right == ‘)‘; } else if (left == ‘[‘) { return right == ‘]‘; } else { return right == ‘}‘; } } }
【leetcode 】20. Valid Parentheses
原文:http://www.cnblogs.com/lanhj/p/5372713.html