Skip to content

Latest commit

 

History

History

20-ValidParentheses

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Valid Parentheses

Problem can be found in here!

def isValid(s: str) -> bool:
    stack = []
    bracket = {"(": ")", "[": "]", "{": "}"}
    for char in s:
        # Case 1: Left Bracket, just simply push into stack
        if char in set("([{"):
            stack.append(char)
        # Case 2: Right Bracket, may cause invalid parentheses
        else:
            if not stack or bracket[stack[-1]] != char:
                return False
            else:
                stack.pop()

    return not stack

Time Complexity: O(n), Space Complexity: O(n)