一、题目概述
二、思路方向
三、代码实现
import java.util.Stack;
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
// 如果是左括号,则压入栈中
stack.push(c);
} else if (c == ')' || c == '}' || c == ']') {
// 如果是右括号,则需要进行匹配判断
if (stack.isEmpty()) {
// 栈为空,说明没有对应的左括号,返回false
return false;
}
char topChar = stack.pop(); // 弹出栈顶元素
if ((c == ')' && topChar != '(') ||
(c == '}' && topChar != '{') ||
(c == ']' && topChar != '[')) {
// 括号不匹配,返回false
return false;
}
}
}
// 如果栈为空,说明所有括号都正确匹配,返回true;否则返回false
return stack.isEmpty();
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.isValid("()")); // true
System.out.println(solution.isValid("()[]{}")); // true
System.out.println(solution.isValid("(]")); // false
System.out.println(solution.isValid("([)]")); // false
System.out.println(solution.isValid("{[]}")); // true
}
}
执行结果:
四、小结
结语