每天刷LeetCode——D1【简单题】

题目编号:

0020:validParentheses
https://leetcode.com/problems/valid-parentheses/description

题目描述:

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: “()”
Output: true
Example 2:

Input: “()[]{}”
Output: true
Example 3:

Input: “(]”
Output: false
Example 4:

Input: “([)]”
Output: false
Example 5:

Input: “{[]}”
Output: true

算法思路

1)使用栈来存储括号
2)遇到左括号进栈,遇到右括号时与栈顶元素比较,如果匹配则出栈,否则匹配失败
3)遇到非括号类元素直接跳过,最终栈为空则匹配成功

Python实现

# =============================================================================
# 解决方案类
# =============================================================================
class Solution:
    #判断方法
    def isValid(self,s):
        #1)栈
        stack=[]
        #2)遍历
        for i in s:
            #进栈
            if i == '{' or i =='(' or i =='[':
                print('符号%s进栈'%i)
                stack.append(i)
            #出栈判断
            if i == '}':
                print("符号'}'进行判断")
                if stack.pop()=='{': pass
                else:return 'false'
            if i == ')':
                print("符号')'进行判断")
                if stack.pop()=='(': pass
                else: return 'false'            
            if i == ']':
                print("符号']'进行判断")
                if stack.pop()=='[': pass
                else: return 'false'  
        #栈是否为空  
        if len(stack)==0:
            return 'true'
        else: 
            print('aaa')
            return 'false'
    
    #判断方法——使用map更简单
    def isvalid2(self,s):
        #1)栈
        stack=[]
        map = {
            "{":"}",
            "[":"]",
            "(":")"
        }
        #2)遍历
        for i in s:
            if i in map:
                stack.append(map[i])
            else:
              if len(stack)!=0:
                top_element = stack.pop()
                if i != top_element:
                  return False
                else:
                  continue
              else:
                return False                                                
        return len(stack) == 0    
    
# =============================================================================
# 测试方法   
# =============================================================================
test=Solution() 
print(test.isValid('abc'))   #true
print(test.isValid('{[([])]}'))   #true
print(test.isValid('{[([]})')) #false
#测试方法2
print(test.isvalid2('{[([])]}'))   #true
print(test.isvalid2('{[([]})')) #false

小结

使用python中自带的map会更加方便

Python的continue和pass的区别:
continue表示跳过后面的程序,重新循环,而pass表示站位,后面的代码(else之前)还是会执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值