๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[Programmers] [์›”๊ฐ„ ์ฝ”๋“œ ์ฑŒ๋ฆฐ์ง€ ์‹œ์ฆŒ2] [Python] Level2_๊ด„ํ˜ธ ํšŒ์ „ํ•˜๊ธฐ

Dbswnstjd 2022. 10. 14. 20:23

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/76502

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 2๋‹จ๊ณ„ - ์›”๊ฐ„ ์ฝ”๋“œ ์ฑŒ๋ฆฐ์ง€ ์‹œ์ฆŒ2 - ๊ด„ํ˜ธ ํšŒ์ „ํ•˜๊ธฐ
from collections import deque
def check(s):
    answer = 0
    stack = []
    for i in s:
        if len(stack) == 0:
            stack.append(i)
        else:
            if i == ')' and stack[-1] == '(':
                stack.pop()
            elif i == '}' and stack[-1] == '{':
                stack.pop()
            elif i == ']' and stack[-1] == '[':
                stack.pop()
            else:
                stack.append(i)
    return 1 if len(stack) == 0 else 0
def solution(s):
    answer = 0
    for i in range(len(s)):
        if check(s): answer += 1
        s = s[1:] + s[:1]
    return answer

solution("[](){}")

๋น„์Šทํ•œ ๋ฌธ์ œ๋กœ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ๊ฐ€ ์žˆ๋‹ค. ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ๋ฅผ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ์Šคํƒ์„ ์‚ฌ์šฉํ•˜์˜€๋Š”๋ฐ ์—ฌ๊ธฐ์„œ๋„ ๋˜ํ•œ ์Šคํƒ์„ ์‚ฌ์šฉํ•˜์˜€๋‹ค. 

์—ด๋ฆฐ ๊ด„ํ˜ธ๊ฐ€ ๋‚˜์˜ค๋ฉด ์Šคํƒ์˜ ๋์— ์ถ”๊ฐ€ ํ•ด์ฃผ๊ณ  ๋‹ซํžŒ ๊ด„ํ˜ธ๊ฐ€ ๋‚˜์˜ค๋ฉด ์Šคํƒ์— ์žˆ๋Š” ์›์†Œ๋ฅผ ํ™•์ธํ•ด ๊ฐ™์€ ๊ด„ํ˜ธ๋ฉด ์Šคํƒ์—์„œ ์ œ๊ฑฐํ•ด ์ค€๋‹ค.