iT邦幫忙

2022 iThome 鐵人賽

DAY 8
0
自我挑戰組

LeetCode Top 100 Liked系列 第 8

[Day 08] Valid Parentheses (Easy)

  • 分享至 

  • xImage
  •  

20. Valid Parentheses

Question

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.
  3. Every close bracket has a corresponding open bracket of the same type.

Example 2

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

Solution 1: Hash + Stack

class Solution:
    def isValid(self, s: str) -> bool:
        dic = {
            '(' : ')',
            '{' : '}',
            '[' : ']'
        }
        
        stack = []
        for i in s:
            if i in dic:
                stack.append(i)
            else:
                if not stack:
                    return False
                
                top = stack.pop()
                if dic[top] != i:
                    return False
        return not stack

Time Complexity: O(N)
Space Complexity: O(N)

Solution 2: Stack

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for i in s:
            if i == '(':
                stack.append(')')
            elif i == '{':
                stack.append('}')
            elif i == '[':
                stack.append(']')
            elif (not stack) or (stack.pop() != i):
                return False
        return not stack

Time Complexity: O(N)
Space Complexity: O(N)

Reference

https://leetcode.com/problems/valid-parentheses/discuss/9178/Short-java-solution

Follow-up: Check if a Parentheses String Can Be Valid

TODO

Time Complexity: O()
Space Complexity: O()


上一篇
[Day 07] Trapping Rain Water (Hard)
下一篇
[Day 09] Regular Expression Matching (Hard)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言