0020. Valid Parentheses

Easy | String + Stack | 24 ms (95.97%), 14.3 MB (64.31%)

Source: LeetCode - Valid Parentheses GitHub: Solution / Performance

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.

Use the hash table to record the mapping of parentheses and the stack to store left-side parenthesis for further verification when meeting right-side parenthesis.

  • return False if first char is a right-side parenthesis

  • return False if the stack is already empty but there is an incoming parenthesis

  • return False if the incoming parenthesis doesn't match with the popped item

Note that we need to check whether the stack is empty before returnning the answer. If the stack is not empty but there are no incoming parentheses, return False.

class Solution:
    def isValid(self, s: str) -> bool:
        # (base case)fy
        if len(s) == 1: return False
        
        # ==================================================
        #  String + Stack                                  =
        # ==================================================
        # time  : O(n)
        # space : O(n)
        
        table = { 
            ')': '(', 
            ']': '[', 
            '}': '{' 
        }
        stack = []
        
        # return False if first char is right-side parenthesis
        if s[0] in table: return False
        
        for char in s:
            if char in table:
                # return False if stack is already empty
                if not stack: return False 
                
                if stack.pop() != table[char]: return False
                
            else:
                stack.append( char )
                
        # check stack's capacity before returning True
        return not stack

Last updated