Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

public class Solution {
    public boolean validMatch(char c1, char c2) {
        if (c1=='(' && c2==')')
            return true;
        if (c1=='{' && c2=='}')
            return true;
        if (c1=='[' && c2==']')
            return true;
        return false;
    }

    public boolean isValid(String s) {
        if (s==null) {
            return true;
        }
        Stack<Character> stack = new Stack<Character>();
        char[] chars = s.toCharArray();
        for (int i=0;i<chars.length;i++) {
            if (stack.empty()) {
                stack.push(chars[i]);
            }else if (validMatch(stack.peek(), chars[i])) {
                stack.pop();
            } else {
                stack.push(chars[i]);
            }
        }
        return stack.empty();
    }
}
原文地址:https://www.cnblogs.com/23lalala/p/3506895.html