LeetCode算法学习(8)

本文详细解析了括号匹配问题的解决思路,通过使用栈的数据结构实现有效的括号验证算法。文章提供了完整的代码示例,并解释了如何判断输入字符串中的括号是否正确配对。

题目描述

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

An input string is valid if:

1.Open brackets must be closed by the same type of brackets.
2.Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

题目大意

括号匹配。

思路分析

简单的栈的应用。

关键代码

    bool match(char a, char b) {
        if (a == '(') return b == ')';
        if (a == '[') return b == ']';
        if (a == '{') return b == '}';
        return false;
    }

    bool isValid(string s) {
        stack<char> stack1;
        int n = s.length();
        for (int i = 0; i < n; i++) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
                stack1.push(s[i]);
            } else if (stack1.empty()) {
                return false;
            } else {
                if (match(stack1.top(), s[i])) {
                    stack1.pop();
                } else {
                    return false;
                }
            }
        }
        if (stack1.empty()) {
            return true;
        } else {
            return false;
        }
    }

总结

当复习栈吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值