文章--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;
}
}

浙公网安备 33010602011771号