leet_20_Valid_Parentheses.py

本文介绍了一个简单的Python程序,用于检查包含括号的字符串是否有效。有效的字符串需要满足:相同类型的括号必须正确闭合,且闭合顺序正确。文章通过两个不同的Python函数实现这一功能,并提供了示例代码。

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

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

def valid(parentheses):
    pairs_list = []
    par = ["([{", ")]}"]
    for i in parentheses:
        if i in par[0]:
            pairs_list.append(i)
        elif i in par[1] and not len(pairs_list):
                return False
        elif i in par[1] and pairs_list[len(pairs_list) - 1] == par[0][par[1].index(i)]:
            pairs_list.pop()
        else:
            pass
    if len(pairs_list):
        return False
    else:
        return True


if __name__ == "__main__":
    parentheses = input("please input the parentheses")
    print("valid is :", valid(parentheses))

more pythonic:

def valid(parentheses):
    map = {')': '(', ']': '[', '}': '{'}
    list = []
    for e in parentheses:
        if e in map and (list and list[-1] == map[e]):
            list.pop()
        else:
            list.append(e)
            #print(e)
    return not list

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值