Problem Link: https://leetcode.com/problems/valid-parentheses/
Valid Parentheses - LeetCode
Can you solve this real interview question? Valid Parentheses - Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the sam
leetcode.com
Solution 1. Stack
Python의 list에서 append 및 pop 연산은 O(1)이므로, 따로 stack을 구현하지 않았다.
Time: $O(N)$
Space: $O(N)$
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
str_len = len(s)
seen = dict()
LEFT = ['(', '[', '{']
RIGHT = [')', ']', '}']
PAIR = {'(': ')', '[': ']', '{': '}'}
stack = []
for par in s:
if par in LEFT:
stack.append(par)
else:
if len(stack) == 0:
return False
left = stack.pop()
pair = PAIR[left]
if pair == par:
continue
else:
return False
if len(stack) > 0:
return False
else:
return True
장황한 코드를 지우고 Discussion의 코드를 토대로 작성하였더니 32ms에서 11ms 정도로 실행시간이 감소했다.
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
str_len = len(s)
seen = dict()
LEFT = ['(', '[', '{']
RIGHT = [')', ']', '}']
PAIR = {'(': ')', '[': ']', '{': '}'}
stack = []
for par in s:
if par in LEFT:
stack.append(par)
elif len(stack) == 0 or PAIR[stack.pop()] != par:
return False
return len(stack) == 0
'Problem Solving' 카테고리의 다른 글
[Leetcode] 226. Invert Binary Tree (0) | 2023.07.13 |
---|---|
[Leetcode] 125. Valid Palindrome (0) | 2023.07.12 |
[Leetcode] 121. Best Time to Buy and Sell Stock (0) | 2023.07.12 |
[Leetcode] 167. Two Sum II - Input Array Is Sorted (0) | 2023.07.11 |
[Leetcode] 1. Two Sum (0) | 2023.07.11 |