##问题描述
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.
##问题分析
该问题即字符串匹配,解决该这类型问题最好使用,队列、堆栈数据结构
堆栈是一个不错的想法在解决匹配的时候需要用到两个值,考虑hashmap的key-value模式
##java代码
public class Solution {
public boolean isValid(String s) {
char[] chars = s.toCharArray();
Map<Character,Character> pairs = new HashMap<Character,Character>();
//key-value
pairs.put('(',')');
pairs.put('[',']');
pairs.put('{','}');
Stack<Character> stack = new Stack<Character>();
for(char c:chars){
//key=c,对应的value是否存在,存在返回true
if(pairs.containsKey(c)){
//获取value
stack.push(pairs.get(c));
} else{
if(stack.isEmpty() || c != stack.pop() ){
return false;
}
}
}
return stack.isEmpty();
}
}