Valid Parentheses

博客围绕LeetCode上一道简单级别题目展开,题目要求判断包含特定括号字符的字符串是否有效。分析得出这是典型的栈结构问题,先进入的左括号最后匹配右括号,遇右括号出栈,若不匹配则字符串不合法,最后栈长度应为0。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetCode https://leetcode.com/problems/valid-parentheses/

简单级别题目

Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

分析题目大致可以得出这个是一个典型的栈结构
先进入的左边符号必定在最后遇到自己的右边符号,并且一旦遇到一个右边括号,就要进行出栈,如果出栈的符号与自己不匹配那么就不是合法字符。并且最后栈的长度一定为0

class Solution {
    public boolean isValid(String s) {
        Stack<String> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            String a = s.substring(i, i + 1);
            if (a.equals("(") || a.equals("[") || a.equals("{")) {
                    stack.push(a);
            } else {
                if (stack.size() > 0) {
                    if (a.equals(")") && !stack.pop().equals("(")) {
                        return false;
                    } else if (a.equals("}") && !stack.pop().equals("{")) {
                        return false;
                    } else if (a.equals("]") && !stack.pop().equals("[")) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }
        if (stack.size() > 0)
            return false;
        return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值