0
点赞
收藏
分享

微信扫一扫

Leetcode JAVA刷刷站(20)有效的括号

小龟老师 2024-08-14 阅读 23

一、题目概述

二、思路方向 

三、代码实现  

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  
    }  
}

执行结果: 

四、小结 

 结语   

举报

相关推荐

0 条评论