leetcode 20 Valid Parentheses - Python

题目:Valid Parentheses 有效的括号

Link: Loading...Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.https://leetcode.com/problems/valid-parentheses/

20. Valid Parentheses

Easy

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

 

-  题目解释和基本思路:

这道题目的意思是给我们一个s,string,需要判断这个string是否是有一对对标准的括号组合组成的。题目中向我们解释了合理组合的规则,就是说,假如出现了:

 (   /    {   /  [   ,那么后面需要出现相对应和括号类型的另一半。在这个思路上我们就很好进行规划了,

- 使用stack作为方法, 存储待处理的符号

- 对括号分成两组,一组为开始的括号组别,一组为结束的括号类型

那么我们来看下code

class Solution(object):

    def valid_parentheses(self, s: str) -> bool:
        """
        """
        stack = []  # storage the ele that need to handle 
        opened = ['(', '{', '[']  # define the group 
        closed = [')', '}', ']']

        for sub in s:
            # sub is from open, put into the stack
            # sub is from close:
                # case one: is a valid close, pop stack[-1], continue
                # case two: is an invalid close, return False
            if sub in opened:
                stack.append(sub)
            else:
                if len(stack) > 0 and stack[-1] == opened[closed.index(sub)]:
                    stack.pop()
                else:
                    return False
            
            return not stack

这里有几个需要注意的地方:

首先, 在对属于closed之中的sub处理的时候。需要是stack之中存在ele的时候,

第二,最后return的判定是为了防止stack之中有还没有处理过得opened sub.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值