LeetCode No.20 Valid Parentheses

来源:互联网 发布:nginx golang 编辑:程序博客网 时间:2024/05/17 04:42
/**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.Subscribe to see which companies asked this question.*/public class Solution {    public boolean isValid(String s) {        Stack<Character> stack = new Stack<Character>();        for (char c : s.toCharArray()) {            if (c == '(')                stack.push(')');            else if (c == '{')                stack.push('}');            else if (c == '[')                stack.push(']');            else if (stack.isEmpty() || stack.pop() != c)                return false;        }        return stack.isEmpty();    }}
0 0