DEV Community

ishwar kokkili
ishwar kokkili

Posted on

Day 2 - Valid Parentheses

-> 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.
Enter fullscreen mode Exit fullscreen mode

Eg ->

Input: s = "()"
Output: true

class Solution:
    def isValid(self, s: str) -> bool:
        stack =[]
        for i in s: 
            if i == "(" or i == "{" or i == "[" : 
                stack.append(i)
            elif i == ")" : 
                if stack and stack[-1]=="(": 
                     stack.pop()
                else: 
                    stack.append(i)
            elif i == "}" : 
                if stack and stack[-1]=="{": 
                    stack.pop()
                else: 
                    stack.append(i)
            elif i == "]" : 
                if stack and stack[-1]=="[": 
                    stack.pop()
                else: 
                    stack.append(i)

        if stack:
            return False 
        else: 
            return True


Enter fullscreen mode Exit fullscreen mode

Discussion (0)