Valid Parentheses
From LeetCode
problem description / solution
Solution in Python3
class Solution:
def isValid(self, s: str) -> bool:
pairs = {
'(': ')',
'{': '}',
'[': ']'
}
stack = []
for c in s:
if c in pairs:
stack.append(c)
elif not stack or pairs[stack.pop()] != c:
return False
return not stack
I am lucky to get
Runtime: 36 ms, faster than 86.12% of Python3 online submissions for Valid Parentheses.
Time Complexity
\(O(l)\), where \(l\) is the length of s
.
Comments