文章--LeetCode算法--ValidParentheses

ValidParentheses

问题描述

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) {
            Map<Character, Character> pM = new HashMap<Character, Character>();
            pM.put('(', ')');
            pM.put('{', '}');
            pM.put('[', ']');
            Stack<Character> pS = new Stack<Character>();
            for (Character c : s.toCharArray()) {
                if (pM.containsKey(c)) {
                    pS.push(pM.get(c));
                }
                else {
                    if (pS.isEmpty() || c != pS.pop())
                        return false;
                }
            }
            if (!pS.isEmpty())
                return false;
            return true;
        }
    }
posted @ 2019-07-22 11:14  AI,me  阅读(55)  评论(0)    收藏  举报