leetcode Valid Parentheses

来源:互联网 发布:淘宝店铺怎么找回 编辑:程序博客网 时间:2024/06/06 02:41

题目:

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 boolean isValid(String s) {        Stack<Character> symbol = new Stack<Character>();        for (int i = 0; i < s.length(); i++) {            if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{')                symbol.push(s.charAt(i));            else {                if (symbol.isEmpty())                    return false;                char top = symbol.peek();                if ((top == '(' && s.charAt(i) != ')') || (top == '[' && s.charAt(i) != ']') || (top == '{' && s.charAt(i) != '}')) {                    return false;                }                symbol.pop();            }        }        return symbol.isEmpty();    }


0 0