Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
public boolean isValid(String s) {
//1,解决匹配问题
// 用字典来解决匹配问题,再用栈的时候先考虑需要不要用字典
HashMap map = new HashMap();
map.put('(',')');
map.put('{','}');
map.put('[',']');
//2,初始化一个栈
Stack h = new Stack();
//3,遍历给定的数组,字符串等等,进行判断
for (int i =0;i<s.length();i++){ //java中对于字符串的遍历只能通过该形式
char tem = s.charAt(i); //常用遍历手段
//3.1 特殊字符压入栈
if (tem =='('||tem == '['||tem=='{') h.push(tem);
else if (h.empty()) return false;
//3.2 特殊字符弹出栈
else if (tem!=(char)map.get(h.pop())) return false;
}
//4 最后检验栈中有无剩余
return h.empty();
解决栈问题的一般步骤