lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

  • leetcode

    • 数组

    • 位运算

    • 动态规划

    • 链表

    • 栈

      • 20.有效的括号
        • 需要注意的点
      • 155.最小栈
    • 树

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • leetcode
  • stack
2023-04-29
目录

有效的括号

https://leetcode-cn.com/problems/valid-parentheses/submissions/ (opens new window)

# JavaScript 解法

var isValid = function(s) {

    const arr = [...s]
    if(arr.length <=1) return false
    const stack = []
    const hashmap = {
        ")": "(",
        "]": "[",
        "}": "{"
    }

    for(let i=0; i< arr.length; i++){
        if(arr[i] in hashmap){
            if(!stack.length ||stack.pop() != hashmap[arr[i]]){
                return false
            }
        }else{
            stack.push(arr[i])
        }
    }
    return !stack.length
   
};

# 需要注意的点

# Python 解法

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) % 2 == 1 :
            return False


        """ 
            pairs 字典
            key,是右边符号,分别是],),}
            value,是左边符号,分别是[,{,(
        """
        pairs = {
            '}': '{',
            ')': '(',
            ']': '['
        }
        
        # 用list 模拟栈
        slist = list()
        for ch in s:
            # 判断 ch 是否在pairs,是的话判断是否符合栈里最后一位相同,否则添加进栈
            if ch in pairs:
                """
                    这里的判断有两个作用
                    1>判断栈非空,也就是第一个元素是右边符号,即],),}
                    2>判断栈最后一位跟字典最后一位是否相同
                """
                if not slist or slist[-1] != pairs[ch]:
                    return False
                slist.pop()

            else:
                slist.append(ch)


        return not slist
234.回文链表
155.最小栈

← 234.回文链表 155.最小栈→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式