ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

https://app.codility.com/programmers/lessons/7-stacks_and_queues/brackets/

 

Brackets coding task - Learn to Code - Codility

Determine whether a given string of parentheses (multiple types) is properly nested.

app.codility.com

 


๋ฌธ์ œ ํ’€์ด

๊ด„ํ˜ธ๊ฐ€ ์˜ฌ๋ฐ”๋ฅธ ์Œ์„ ์ด๋ฃจ๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ฌธ์ œ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด ({)} ์ด๋ฉด ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ์Œ ์ด์ง€๋งŒ (}){ ์ผ ๊ฒฝ์šฐ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ์Œ์ด ์•„๋‹ˆ๋‹ค.

 


์ฝ”๋“œ

def solution(S):
    stack = []
    opens = ('{', '[', '(')
    close = ('}', ']', ')')

    for char in S:
        if char in opens:
            stack.append(char)
        else:
            if not stack:
                return 0
            elif opens.index(stack.pop()) == close.index(char):
                continue
            else:
                return 0

    return 1 if not stack else 0
  • ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ค‘ { { { {๊ฐ€ ์ž…๋ ฅ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค. ์ด๋ฅผ ์œ„ํ•ด stack์— ๊ฐ’ ์กด์žฌ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•˜์—ฌ์•ผ ํ•œ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€