给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = “()”
输出:true
示例 2:
输入:s = “()[]{}”
输出:true
示例 3:
输入:s = “(]”
输出:false
示例 4:
输入:s = “([)]”
输出:false
示例 5:
输入:s = “{[]}”
输出:true
1.原想直接用单调栈的模板来做,其实完全不适合
class Solution {
public boolean isValid(String s) {
Deque<Character> st = new ArrayDeque<>();
char ch[] = s.toCharArray();
HashMap<Character, Character> map = new HashMap<>();
map.put(')', '(');//首先这些应当放到构造函数里面
map.put(']', '[');
map.put('}', '{');
for(char c : ch){
//这里也不应使用while,一般只需要出一次栈即可
while(!st.isEmpty() && (c == ')' || c == ']' || c == '}')){
if(st.peek() != map.get(c)) return false;
st.pop();
}
st.push(c);//这里不是所有元素都要加入栈,只有左括号才需要加入,所以需要判断一下
}
return st.isEmpty();
}
}
class Solution {
HashMap<Character, Character> map = new HashMap<>();
public Solution(){
//放到这里初始化,这样就只进行一次即可
map.put(')', '(');
map.put('}', '{');
map.put(']', '[');//反着存储
}
public boolean isValid(String s) {
Deque<Character> st = new ArrayDeque<>();
char ch[] = s.toCharArray();
for(char c : ch){
if(c == ')' || c == ']' || c == '}'){// if(map.containsKey(c)相同效果
if(st.isEmpty()) return false;
if(st.peek() != map.get(c)) return false;
st.pop();
}else {
st.push(c);
}
}
return st.isEmpty();
}
}