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.
tag : stack, string
注意: hashmap。 map.keySet().contains(key). map.values().contains(value) 方法
public class Solution {
public boolean isValid(String s) {
if(s == null || s.length() == 0){
return true;
}
if(s.length() % 2 != 0){
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 cur = s.charAt(i);
if(map.keySet().contains(cur)){
stack.push(cur);
}else if(map.values().contains(cur)){
if(!stack.isEmpty() && map.get(stack.peek()) == cur){
stack.pop();
}else{
return false;
}
}
}
return stack.isEmpty();
}
}
原文:http://www.cnblogs.com/superzhaochao/p/6396716.html