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

  • 相关阅读:
    Golang 开发环境安装和配置
    多测师肖老师__接口测试之cms搭建(27.1)
    多测师肖老师__接口测试之fn+f12查看接口(27.2)
    认识wpf中binding类型
    认识wpf的事件
    Jquery对象与Dom对象
    AS3编程中的两种常用事件
    SQL Server 系统表简介
    Winform中ComcoBox控件设置选定项
    wpf开篇入门
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8397499.html
Copyright © 2011-2022 走看看