3.LeetCode20 Valid Parentheses 笔记

1:题目描述

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

判断输入的括号是否匹配

2:题目分析

括号匹配正确的情况下,第一个闭括号与他之前的第一个左括号肯定对应。python中的列表可以删除元素值,所以只需查看列表第一个右括号是否对应它前面的第一个括号,如果对应,删除这对括号;如果不对应,返回错误。最后列表如果是空的,则匹配正确,否则错误。

3:解题过程(代码)

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s_len=len(s) 
        temp=[]   #设置temp列表储存左括号
        i=0
        j=0
        while i<s_len:  #遍历括号
            temp.append(s[i])  #temp列表添加括号
            j=len(temp)-1        #获取当前列表最后一位的索引位置
            if temp[j]==')':        #指向列表的最后一个元素
                if temp[j-1]=='(':  #如果匹配,删除这对括号
                    del temp[j]
                    del temp[j-1]
                else:
                    break
                    return False
            elif temp[j]==']':
                if temp[j-1]=='[':
                    del temp[j]
                    del temp[j-1]
                else:
                    return False
            elif temp[j]=='}':
                if temp[j-1]=='{':
                    del temp[j]
                    del temp[j-1]
                else:
                    return False
            i=i+1
        if len(temp)==0:   #判断temp列表是否为空
            return True
        else:
            return False

 

4:解题收获

因为python列表可以删除元素,与C的数组不同,所以得到了灵感。第一次感受到用人类思维解决问题的快感 ^_^

转载于:https://www.cnblogs.com/19991201xiao/p/8397499.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值