美文网首页
20. Valid Parentheses

20. Valid Parentheses

作者: 衣介书生 | 来源:发表于2018-04-10 21:47 被阅读3次

题目分析

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.

可以用栈来解决这道题目。时间复杂度为 O(n),空间复杂度为 O(n)。

代码

class Solution {
    public boolean isValid(String s) {
        if(s == null || s.length() == 0) {
            return true;
        }
        Stack<Character> stack = new Stack();
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            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();
    }
}

相关文章

网友评论

      本文标题:20. Valid Parentheses

      本文链接:https://www.haomeiwen.com/subject/ebhohftx.html