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 != 0) {
return false;
}
char[] sArr = s.toCharArray();
HashMap<Character, Character> hm = new HashMap<Character, Character>();
hm.put(')','(');
hm.put('}','{');
hm.put(']','[');
Stack<Character> st = new Stack<Character>();
for(char c : sArr) {
if (!hm.containsKey(c)) {
st.push(c);
} else {
if (st.isEmpty() || st.pop() != hm.get(c)) {
return false;
}
}
}
return st.isEmpty();
}
}