๊ฐ๋ฐ/๐ค ์๊ณ ๋ฆฌ์ฆ
[leetcode][Easy][Stack] 20. Valid Parentheses ํ์ด, ํด์ค (python)
ttoance
2023. 11. 3. 00:52
https://leetcode.com/problems/valid-parentheses/
1์ฐจ ํ์ด
๋จ์ํ ์คํ ๋ฌธ์ ๋ผ ๊ฐ๋จํ ํ์์ง๋ง,
์กฐ๊ฑด์ด ์ถ๊ฐ๊ฐ ๋๋ฉด์ ์ข ๋ณต์กํ ํ์ด๊ฐ ๋์๋ค.
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for c in s:
if c in ['(', '{', '[']:
stack.append(c)
elif c in [')', '}', ']']:
# popํ ๊ฐ์ด ์๋ค๋ฉด
if len(stack) == 0:
return False
t = stack.pop()
if c == ')' and t != '(':
return False
elif c == '}' and t != '{':
return False
elif c == ']' and t != '[':
return False
# ๋ชจ๋๋ค pop ๋์ด์๋ค๋ฉด
if len(stack) == 0:
return True
return False
ํด์ค
https://www.youtube.com/watch?v=WTzjTskDFMg
ํด์ค์ map ํ์์ ์ด์ฉํด์ ์กฐ๊ธ ๋ ๊ฐ๋จํ๊ฒ ํ์๋ค.
stack = []
closeToOpen = {")": "(", "]": "[", "}": "{"}
for c in s:
if c in closeToOpen:
if stack and stack[-1] == closeToOpen[c]:
stack.pop()
else:
return False
else:
stack.append(c)
# ๋น์ด์์ผ๋ฉด true ๋ก ๋ฆฌํด
return True if not stack else False
๋ฐ์ํ