Created
April 9, 2022 15:15
-
-
Save Josephchinedu/752ff9317434df83fb609f82c95c707c to your computer and use it in GitHub Desktop.
Valid Parentheses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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. | |
### steps: | |
# Start with opening parentheses, the number of opening parentheses should equal closing parentheses | |
# we check if the closing parentheses matches the opening parentheses, then we remove it from consideration list | |
# when removing matched parentheses we remove from the last. use pop() function | |
class Solution: | |
def isValid(self, s: str) -> bool: | |
# define and empty stack | |
stack = [] | |
## create a hash map or dictionary that mapp all closing parentheses to the opening ones. | |
closeToOpen = {")":"(", "]":"[", "{":"}"} | |
## loop through every character in the str pass to this function | |
for i in s: | |
# check is this charcater is a closing parentheses | |
if i in closeToOpen: | |
# if this's a close parentheses, let's make sure the stack is not empty and chack the value at the top is the matching opening parentheses | |
# if they match pop the stack list | |
if stack and stack[-1] == closeToOpen[i]: | |
stack.pop() | |
else: | |
return False | |
else: | |
stack.append(c) | |
return True is not stack else False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment