1.题目
20.有效的括号
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 每个右括号都有一个对应的相同类型的左括号
示例 1:
输入:s = “()” 输出:true
2.解题思路
1.栈
创建两个栈,将字符串转为byte类型存入stack1中,遍历stack1,判断stack2中的peek是否为对应的另一半,不是则入栈,是则stack2出栈,最后判断stack2是否为空若为空则证明合理
public boolean isValid(String s) {
Stack<Byte> stack1 = new Stack<>();
Stack<Byte> stack2 = new Stack<>();
byte[] bytes = s.getBytes();
for (int i = 0; i < bytes.length; i++) {
stack1.push(bytes[i]);
}
for (int i = 0; i < bytes.length; i++) {
Byte pop = stack1.pop();
if (stack2.size() == 0) {
stack2.push(pop);
continue;
}
if (pop + 1 == stack2.peek() || pop + 2 == stack2.peek()) {
stack2.pop();
} else {
stack2.push(pop);
}
}
if (stack2.size() == 0) {
return true;
}
return false;
}
2.哈希
其中比较麻烦的是如何判断两个符号是不是一组的,我们可以用哈希表将所有符号先存储,左半边做key,右半边做value。遍历字符串的时候,遇到左半边符号就入栈,遇到右半边符号就与栈顶的符号比较,不匹配就返回false
boolean isValid(String s) {
if(s.length()<=1){
return false;
}
Map<Character,Character> smap = new HashMap<>();
smap.put('(',')');
smap.put('{','}');
smap.put('[',']');
Stack<Character> stack = new Stack<>();
for(int i=0;i<s.length();i++){
char item = s.charAt(i);
if(smap.containsKey(item)){
stack.push(item);
}else{
if(!stack.isEmpty()){
Character left = stack.pop();
char rightchar = smap.get(left);
if(rightchar != item){
return false;
}
}else {
return false;
}
}
}
return stack.isEmpty();
}