728x90
1.Quiz
2.Solution
전형적인 stack 문제. 코드를 깔끔하게 짜도록 연구해야겠다.
다른 사람 코드를 보니 괄호를 미리 정의해두고 닫힘 괄호가 나타나면 stack의 마지막 값을 dict 를 사용하여 짝이 있는지 확인하도록했다.
class Solution:
def isValid(self, s: str) -> bool:
parentheses = {"}":"{", "]":"[", ")":"("}
stack = []
for char in s:
if char in parentheses.keys():
if len(stack) and stack[-1] == parentheses[char]:
stack.pop()
else:
return False
else:
stack.append(char)
return len(stack) == 0
3.Code
class Solution:
def isValid(self, s: str) -> bool:
st = []
for i in s:
if i == '(':
st.append(i)
elif i == '{':
st.append(i)
elif i == '[':
st.append(i)
elif i == ')':
if (len(st) <= 0):
return False
top = st.pop()
if (top != '('):
return False
elif i =='}':
if (len(st) <= 0):
return False
top = st.pop()
if (top != '{'):
return False
else:
if (len(st) <= 0):
return False
top = st.pop()
if ( top != '['):
return False
if (len(st) > 0):
return False
return True
728x90
'코딩 테스트' 카테고리의 다른 글
[HackerRank] Tree: Height of a Binary Tree (Python) (0) | 2025.01.18 |
---|---|
[HackerRank] Balanced Brackets (Python) (0) | 2025.01.18 |
[LeetCode] RansomNote (Python) (0) | 2025.01.15 |
[LeetCode] Find the Index of the First Occurrence in a String (Python) (0) | 2025.01.15 |
[LeetCode] 14.Longest Common Prefix (Python) (0) | 2025.01.15 |