每天刷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之前)还是会执行。

你可能感兴趣的:(LeetCode刷题)