20. Valid Parentheses

来源:互联网 发布:域名紧急更新 编辑:程序博客网 时间:2024/04/30 15:50

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 isValid(String s) {       if(s.length()%2==1 || s.length()==0) return false;        Map<Character, Character> map = new HashMap<Character, Character>();//hashmap存括号对,key存括号左半部分,value存括号有半部分        map.put('(', ')');        map.put('[', ']');        map.put('{', '}');        Deque<Character> stack = new LinkedList<>();//堆栈存括号对的左半部分        for (int i = 0; i < s.length(); i++) {            char curr = s.charAt(i);             //判断字符,如果存在于map中key中,则是左半部分,存于堆栈中。如果存在于map中的value中,则是右半部分,和堆栈中的栈顶元素比较,若相等,括号配对成功;否则返回括号配对失败。            if (map.keySet().contains(curr)) {                stack.addFirst(curr);            } else if (map.values().contains(curr)) {                if (!stack.isEmpty() && map.get(stack.getFirst()) == curr) {                    stack.removeFirst();                } else {                    return false;                }            }        }        return stack.isEmpty();    }}
0 0
原创粉丝点击