Leetcode-Easy 20. Valid Parentheses

简介: Leetcode-Easy 20. Valid Parentheses

20. Valid Parentheses


  • 描述:
    判断括号是否匹配 (),{},[]

    3.png
  • 思路:
    遍历括号字符串,添加到一个数组中,匹配数组最后一个元素和当前遍历的字符是否匹配,如果匹配弹出一个元素,如果不匹配,添加一个元素,最后判断数组的长度是否为0.(利用栈的思想)


  • 代码

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        dict={"()","[]","{}"}
        arr=[]
        for i in range(len(s)):
            if len(arr)!=0 and (arr[-1]+s[i]) in dict:
                arr.pop()
            else:
                arr.append(s[i])
        return len(arr)==0


相关文章
|
26天前
|
存储 SQL 算法
LeetCode 题目 65:有效数字(Valid Number)【python】
LeetCode 题目 65:有效数字(Valid Number)【python】
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
LeetCode 367. Valid Perfect Square
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
78 0
LeetCode 367. Valid Perfect Square
LeetCode 301. Remove Invalid Parentheses
删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。 说明: 输入可能包含了除 ( 和 ) 以外的字符。
56 0
LeetCode 301. Remove Invalid Parentheses
LeetCode 242. Valid Anagram
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
57 0
LeetCode 242. Valid Anagram
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
59 0
LeetCode 241. Different Ways to Add Parentheses
|
canal
LeetCode 125. Valid Palindrome
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
73 0
LeetCode 125. Valid Palindrome
|
算法
LeetCode 65. Valid Number
验证给定字符串是否可以解释为十进制数。
73 0
LeetCode 65. Valid Number
LeetCode 20:有效的括号 Valid Parentheses
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 有效字符串需满足: 左括号必须用相同类型的右括号闭合。
745 0
|
21天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题