LeetCode - 解题笔记 - 20 - Valid Parentheses

本文解析经典编程问题ValidParentheses的两种解决方案,探讨如何利用栈来验证括号的有效配对。通过Python实现,涉及时间复杂度和空间复杂度分析,适合初学者理解括号匹配原理。

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

Valid Parentheses

Solution 1

经典的栈练习题。需要注意两个判定条件:括号类型的搭配以及方向(先右后左不能配对)。

  • 时间复杂度:O(N)O(N)O(N)NNN为输入字符串的长度,遍历需要
  • 空间复杂度:O(N)O(N)O(N)NNN为输入字符串的长度,栈的数据需要
class Solution {
public:
    bool isValid(string s) {
        stack<char> check;
        map<char, int> parenthese;
        parenthese['('] = -1;
        parenthese[')'] = 1;
        parenthese['['] = -2;
        parenthese[']'] = 2;
        parenthese['{'] = -3;
        parenthese['}'] = 3;
        for (auto c: s) {
            if (!check.empty() && parenthese[check.top()] + parenthese[c] == 0 && parenthese[check.top()] < parenthese[c]) {
                check.pop();
            }
            else {
                check.push(c);
            }
        }
        
        if (check.empty()) {
            return true;
        }
        else {
            return false;
        }
    }
};

Solution 2

Solution 1的Python实现,头一次留意到Python的列表是对应了栈的实现的。

class Solution:
    def isValid(self, s: str) -> bool:
        parenthese = {'(': -1, ')': 1, '[': -2, ']': 2, '{': -3, '}': 3}
        
        check = list()
        
        for c in s:
            if len(check) > 0 and parenthese[check[-1]] + parenthese[c] == 0 and parenthese[check[-1]] < parenthese[c] :
                check.pop()
            else :
                check.append(c)
                
        if len(check) != 0:
            return False
        else:
            return True
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值