题目:
代码示例:
package com.zy.leetcode.LeetCode_20;
import java.util.Stack;
/**
* @Author: zy
* @Date: 2025-01-08-12:28
* @Description:
*/
public class LeetCode_20 {
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if (c == ')' && top != '(' || c == '}' && top != '{' || c == ']' && top != '[') {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String s = "()";
System.out.println(isValid(s)); // true
s = "([)]";
System.out.println(isValid(s)); // false
s = "{[]}";
System.out.println(isValid(s)); // true
s = "([)]";
System.out.println(isValid(s)); // false
s = "}";
System.out.println(isValid(s)); // false
}
}