Created
June 20, 2017 06:07
-
-
Save farkwun/91ba5dd4de3a9bdecba6d76d5c0ba910 to your computer and use it in GitHub Desktop.
20. Valid Parentheses - Leetcode
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
# https://leetcode.com/problems/valid-parentheses/#/description | |
class Solution(object): | |
CLOSED_BRACKET_DICT = { | |
')' : '(', | |
'}' : '{', | |
']' : '[' | |
} | |
def isValid(self, s): | |
""" | |
:type s: str | |
:rtype: bool | |
""" | |
stack = [] | |
for c in s: | |
if c == '(' or c == '{' or c == '[': | |
stack.append(c) | |
else: | |
if c in self.CLOSED_BRACKET_DICT: | |
if stack and stack[-1] == self.CLOSED_BRACKET_DICT[c]: | |
stack.pop() | |
continue | |
else: | |
return False | |
if stack: | |
return False | |
else: | |
return True | |
1 char variables are okay as long as you explain them. But I'd generally shy away from c and s even though it's fairly self explanatory in this context.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe people tend to prefer immediate
return
rather than anelse: return
(at least in my workplace they do).More SO discussion. I tend to agree as verbosity is annoying.
e.g.
Preferable: