Created
February 11, 2021 16:58
-
-
Save wilfreddesert/2984f0a0087adac3dee6d25c1bfbf7f2 to your computer and use it in GitHub Desktop.
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
def is_balanced(exp: AnyStr) -> bool: | |
""" | |
Time Complexity: O(n) | |
Space complexity: O(n) | |
>>> s = "()[]{}" | |
>>> is_balanced(s) | |
True | |
>>> s = "([)]" | |
>>> is_balanced(s) | |
False | |
>>> s = "{[]}" | |
>>> is_balanced(s) | |
True | |
>>> s = "()" | |
>>> is_balanced(s) | |
True | |
""" | |
opening = ["(", "[", "{"] | |
closing = [")", "]", "}"] | |
mapping = dict(zip(closing, opening)) | |
stack = [] | |
for char in exp: | |
if char in closing: | |
if not stack or stack[-1] != mapping[char]: | |
return False | |
stack.pop() | |
else: | |
stack.append(char) | |
return not stack |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment