• 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的数组不同,所以得到了灵感。第一次感受到用人类思维解决问题的快感 ^_^

  • 相关阅读:
    Spring事务管理
    Spring Bean装配(下)——注解
    Spring Bean装配(上)
    Spring入门篇
    Spring入门篇——AOP基本概念
    计算机组成原理(1)——系统概述
    浏览器缓存 总结
    React-router 4 总结
    Redux 总结
    操作系统位数 的 概念(转)
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8397499.html
Copyright © 2020-2023  润新知