LeetCode [栈] 20.Valid Parentheses (C++和Python实现)

20 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.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

【解题C++】

很经典的一道题啦~不多说,都在注释里。

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        for(int i=0;i<s.length();i++)
        {
            //如果栈为空,直接入栈
            if(st.empty())
                st.push(s[i]);
            //如果栈中有符号,将它和准备入栈的符号进行对比,匹配的话,栈中符号出栈
           else if((st.top()=='('&&s[i]==')')||(st.top()=='['&&s[i]==']')||(st.top()=='{'&&s[i]=='}'))
                st.pop();
            //否则,继续入栈
            else
                st.push(s[i]);
        }
        //最后如果栈为空,说明匹配成功
        return st.empty();
    }
};

【解题Python】

自己开头写了一个巨垃圾的代码,看完官方题解默默删掉重来= = 思路是一样的,但是Python可以写得更灵活一些,看来我应该多熟悉一下Python的语法了。

class Solution:
    def isValid(self, s: str) -> bool:
        # 字典大法好!!!注意这里是右边符号:左边符号
        mapping = {')':'(',']':'[','}':'{'}
        # 用列表模拟栈
        stack = []
        for str in s:
            # 如果当前字符为右边括号
            if str in mapping:
                # 如果栈不为空,弹出栈顶元素并赋值给top,不然赋个无效值
                top = stack.pop() if stack else '#'
                # 如果栈顶元素不是匹配的左括号,返回错误
                if mapping[str] != top:
                    return False
            # 如果当前字符为左边括号,入栈
            else:
                stack.append(str)
        # 栈为空,返回正确
        return not stack
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值