Skip to content

Instantly share code, notes, and snippets.

@farkwun
Created June 20, 2017 06:07
Show Gist options
  • Save farkwun/91ba5dd4de3a9bdecba6d76d5c0ba910 to your computer and use it in GitHub Desktop.
Save farkwun/91ba5dd4de3a9bdecba6d76d5c0ba910 to your computer and use it in GitHub Desktop.
20. Valid Parentheses - Leetcode
# 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
@robin-pham
Copy link

I believe people tend to prefer immediate return rather than an else: return (at least in my workplace they do).
More SO discussion. I tend to agree as verbosity is annoying.

e.g.

        if stack:
            return False
        else:
            return True

Preferable:

        if stack:
            return False
        return True

@robin-pham
Copy link

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