Algorithm(알고리즘)/백준

28_백준 4949번 파이썬 균형잡힌세상

고로케 2021. 6. 22.
반응형

언제 .append 를 하고 언제 .pop 을 할지를 고민하면서 풀이하였다.

그전에 했던 24번_괄호문제와 유사하여 비슷하게 코드를 썼다.

 

24_백준 9012번 파이썬 괄호

스택 문제이다. 적절하게 .append와 .pop을 해주고 조건에 따라 멈추고 비었을때 조건을 하나 더 주는 것이 포인트 (나는 stop 숫자를 넣었다) 풀이 from sys import stdin def push(x): stack.append(x) def pop(..

gorokke.tistory.com

 

코드 설명

if i == '(': ( 이 나오면 ->stack.append()
if i == ')': ) 이 나오면:
if stack and stack[-1] == '(': stack이 비어있지 않고 + stack[-1] 마지막 항이 '(' 일때
   stack.pop() -> stack.pop() 해라
stack이 비어있거나 or stack[-1] != '(' 마지막항이 '(' 이 아니라면
 elif not stack or stack[-1] != '(': #       
  return 1 ->return 1 해라
...

 

  • 풀이
from sys import stdin

def bracket(line):
    for i in line:
        if i == '(' or i == '[':
            stack.append(i)

        if i == ')':
            if stack and stack[-1] == '(':
                stack.pop()
            elif not stack or stack[-1] != '(':
                return 1

        if i == ']':
            if stack and stack[-1] == '[':
                stack.pop()
            elif not stack or stack[-1] != '[':
                return 1
    return 0


while True:
    stack = []
    line = stdin.readline()
    if line[0] == '.':
        break
    line = ''.join(line.split())

    true = bracket(line)

    if true == 0 and not stack:
        print('yes')
    else:
        print('no')

 

# 입력
So when I die (the [first] I will see in (heaven) is a score list).
[ first in ] ( first out ).
Half Moon tonight (At least it is better than no Moon at all].
A rope may form )( a trail in a maze.
Help( I[m being held prisoner in a fortune cookie factory)].
([ (([( [ ] ) ( ) (( ))] )) ]).
 .
.  <-- 멈춰!
# 출력
yes
yes
no
no
no
yes
yes

 

반응형

댓글