Valid Parentheses Easy
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) { 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; } } return pS.isEmpty(); }
思路:典型的压栈出栈操作,遇左括号则压右括号,右则出栈且对比。对比有不同或最后栈不为空,则失败。