diff --git a/NeetCodeRoadmap/Stack/20_Valid_Parenthesis.py b/NeetCodeRoadmap/Stack/20_Valid_Parenthesis.py new file mode 100644 index 0000000..2de5fce --- /dev/null +++ b/NeetCodeRoadmap/Stack/20_Valid_Parenthesis.py @@ -0,0 +1,26 @@ +def isValid(s): + """ + :type s: str + :rtype: bool + """ + stack = [] # only use append and pop + pairs = { + '(': ')', + '{': '}', + '[': ']' + } + for bracket in s: + if bracket in pairs: + stack.append(bracket) + elif len(stack) == 0 or bracket != pairs[stack.pop()]: # Checks for corresponding dictionary value based on previous closing bracket + return False + print(stack) + return len(stack) == 0 + + + +# print(isValid("()")) # true +print(isValid("()[]{}")) # true +print(isValid("(]")) # false +print(isValid("([)]")) # false +print(isValid("{[]}")) # true diff --git a/Top150Interview/20_Valid_Parenthesis.py b/Top150Interview/20_Valid_Parenthesis.py deleted file mode 100644 index a616052..0000000 --- a/Top150Interview/20_Valid_Parenthesis.py +++ /dev/null @@ -1,31 +0,0 @@ -def isValid(s): - """ - :type s: str - :rtype: bool - """ - pervious = "" - openBracket = ['(', '{', '['] - bracketPairs = ['()', '{}', '[]'] - pairs = None - - for x in s: - if x in openBracket: - previous = x - else: - # print(previous+x) - if (previous+x) in bracketPairs: - pairs = True - else: - return False - return pairs - -print(isValid("()")) -print(isValid("()[]{}")) -print(isValid("(]")) -print(isValid("([)]")) -print(isValid("{[]}")) -print(isValid("{[]}")) -print(isValid("{[]}")) -print(isValid("{[]}")) -print(isValid("{[]}")) -print(isValid("{[]}"))