Leetcode-20: Valid Parentheses

来源:互联网 发布:移动网络垃圾 编辑:程序博客网 时间:2024/06/15 06:18

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.


思路: 括号匹配很简单,数据结构中教过大家使用栈来对括号进行匹配,左括号压栈,有对应的右括号出栈,否则返回false,最终的栈中为空即返回true,否则返回false。


public class Solution {    public boolean isValid(String s) {        Deque<Character> deque = new LinkedList<>();        for (int i = 0; i < s.length(); ++i) {            char c = s.charAt(i);            if ((c == '(') || (c == '[') || (c == '{'))                deque.addFirst(c);            else {                if (deque.isEmpty()) return false;                if (c == ')' && deque.getFirst() != '(' ||                    c == ']' && deque.getFirst() != '[' ||                    c == '}' && deque.getFirst() != '{')                    return false;                deque.removeFirst();                    }        }        return deque.isEmpty();                            }}


原创粉丝点击