728x90
1. 문제
https://www.hackerrank.com/challenges/balanced-brackets/problem
2.풀이
stack을 이용한 기본 문제
3.코드
def isBalanced(s):
st = []
print(s)
for i in range(len(s)):
if (s[i] == "(" or s[i] == "{" or s[i] == "["):
st.append(s[i])
elif s[i] == ")":
if (len(st) <= 0):
return "NO"
cur = st.pop()
if (cur != "("):
return "NO"
elif s[i] == "}":
if (len(st) <= 0):
return "NO"
cur = st.pop()
if (cur != "{"):
return "NO"
elif s[i] == "]":
if (len(st) <= 0):
return "NO"
cur = st.pop()
if ( cur != "["):
return "NO"
if (len(st) > 0):
return "NO"
return "YES"
4.리팩토링
dictionary 사용해서 중복된 코드 제거하기
def isBalanced(s):
stack = []
bracket_dict = {')' : '(', '}': '{', ']':'[' }
for char in s:
if char in bracket_dict.values():
stack.append(char)
elif char in bracket_dict:
if not stack or stack.pop() != bracket_dict[char]:
return "NO"
if (len(stack) > 0):
return "NO"
return "YES"
728x90
'코딩 테스트' 카테고리의 다른 글
[HackerRank] Tree: Level Order Traversal (0) | 2025.01.18 |
---|---|
[HackerRank] Tree: Height of a Binary Tree (Python) (0) | 2025.01.18 |
[LeetCode] Valid Parentheses (Python) (0) | 2025.01.15 |
[LeetCode] RansomNote (Python) (0) | 2025.01.15 |
[LeetCode] Find the Index of the First Occurrence in a String (Python) (0) | 2025.01.15 |
댓글