20. 有效的括号 栈的经典应用,建议先去了解栈的基础
题目链接:https://leetcode.cn/problems/valid-parentheses/ 视频讲解:https://www.bilibili.com/video/BV1AF411w78g
public class Demo3 {
public boolean sS(String s) {
if (s==null||s.length()==0) {
return true;
}
if (s.length()%2!=0) {
return false;
}
Stack<Character> stack=new Stack<>();
for (char c:s.toCharArray()) {
if(c=='(')
stack.push(')');
else if(c=='[')
stack.push(']');
else if(c=='{')
stack.push('}');
else {
if (stack.isEmpty()||stack.pop()!=c) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Demo3 demo3=new Demo3();
String string=in.nextLine();
System.out.println(demo3.sS(string));
}
}