第十一天|20. 有效的括号
题目关键字:栈,不能使用map
20_题目链接:https://leetcode.cn/problems/implement-stack-using-queues/
代码实现
package LeetCode;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class YangSibo_20 {
public static void main (String args []) {
YangSibo_20_1 demo = new YangSibo_20_1();
System.out.println(demo.isValid("(]"));
}
}
class YangSibo_20_1 {
public boolean isValid(String s) {
int length = s.length();
char k1 [] = {'{','}','(',')','[',']'};
Stack<Character> stack = new Stack<>();
for(int i = 0; i < length; i++) {
char c = s.charAt(i);
for (int j = 0; j < 6; j++) {
if( c == k1[j] && (j%2 == 0)) {
stack.push(c);
}else if(c == k1[j]){
char right = k1[j-1];
if (stack.isEmpty()){
return false;
}else if(right == stack.peek()) {
stack.pop();
}else {
return false;
}
}
}
}
if(stack.isEmpty()) {
return true;
}else {
return false;
}
}
}
解题注意事项
1、不能使用map,使用map作为对象映射右括号时找不到,会出现空指针
2、对异常场景做好处理,保证不遗漏