본문 바로가기
코딩 테스트

[HackerRank] Balanced Brackets (Python)

by zoodi 2025. 1. 18.
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

댓글