➜ ~

Playing Hacks and Stuffs!


Project maintained by h4ckyou Hosted on GitHub Pages — Theme by mattgraham

Valid Parentheses

image

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

From the question we know that we’ll be given a string containing the symbols above

Our goal is to check if it’s a valid parenthesis

One way to approach this is to use the Stack Data Structure

The idea basically is this:

Here’s my solve script: link image

Leetcode Submission Script

class Solution:
    def isValid(self, s: str) -> bool:
        parenthesis = {')': '(', '}': '{', ']': '['}
        stack = []

        for char in s:
            if char in parenthesis.values():
                stack.append(char)
            
            elif char in parenthesis.keys():
                if not stack or stack.pop() != parenthesis[char]:
                    return False

        return len(stack) == 0