Leet code刷題筆記

Valid Parentheses -Python解題

困難度:Easy

題目: 如果字串中有相同類型的括號,就判斷為true,沒有則判斷為false。

Given a string s 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.

Example 1:

Input: s = “( )”

Output: true

Example 2:

Input: s = “( )[ ]{ }”

Output: true

Example 3:

Input: s = “( ]”

Output: false

Example 4:

Input: s = “( [ ) ]”

Output: false

Example 5:

Input: s = “{ [ ] }”

Output: true

Python解題筆記

Inline code has back-ticks around it.

class Solution:
    def isValid(self, s):
        temp=['temp']
        tempdist={')':'(','}':'{',']':'['}
        for i in s:
            if i in tempdist and tempdist[i]==temp[len(temp)-1]:
                temp.pop()
            else:
                temp.append(i)
        return len(temp) == 1

題目原處-LeetCode