iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 19
0

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

Constraints:

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


Hint
https://ithelp.ithome.com.tw/upload/images/20201004/20111516x8Zi4UFGq7.png

Recall
(推推)編譯器 Compiler 的 課堂實作有用上。

思路 便 Start Coding

if 欲放進的 括弧 在 stack 的最上面 則移除
else 加進 stack

最後全部括弧走一遍後
如果 stack 為 空 則 return True
否則 return False

正解 即 思路

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        map_pair = {}
        map_pair['('] = ''
        map_pair[')'] = '('
        map_pair['['] = ''
        map_pair[']'] = '['
        map_pair['{'] = ''
        map_pair['}'] = '{'       
        for i in range(len(s)):
            if len(stack)!=0 and map_pair[s[i]] == stack[len(stack)-1]:
                stack.pop()
            else:
                stack.append(s[i])
        if len(stack)==0:
            return True
        else:
            return False

Result
https://ithelp.ithome.com.tw/upload/images/20201004/20111516VWRTjzOYuw.jpg


上一篇
(Medium) 19. Remove Nth Node From End of List
下一篇
(Medium) 22. Generate Parentheses
系列文
刷刷題 or Alan Becker's game 製作 is a question 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言