题目描述
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 static boolean isValid(String s) {
// 字符串长度是奇数,肯定不合法,直接返回false
if (s == null || s.length() % 2 == 1) {
return false;
}
HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.keySet().contains(c)) {
stack.push(c);
} else if (map.values().contains(c)) {
if (!stack.empty() && map.get(stack.peek()) == c) {
stack.pop();
} else {
return false;
}
}
}
return stack.empty();
}