[BOJ] #9935 ๋ฌธ์ž์—ด ํญ๋ฐœ (Python)

    ๋ฐ˜์‘ํ˜•

    ๐ŸŒฑ ๋ฌธ์ œ

     

    9935๋ฒˆ: ๋ฌธ์ž์—ด ํญ๋ฐœ

    ์ฒซ์งธ ์ค„์— ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋Š” 1๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 1,000,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค. ๋‘˜์งธ ์ค„์— ํญ๋ฐœ ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ๊ธธ์ด๋Š” 1๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 36๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค. ๋‘ ๋ฌธ์ž์—ด์€ ๋ชจ

    www.acmicpc.net

     

    ๐ŸŒฑ ํ’€์ด

    1. ์ž…๋ ฅ ๋ฐ›๊ธฐ

    str = deque(list((input().strip())))
    bomb = list(input().strip())

    ์ „์ฒด ๋ฌธ์ž์—ด๊ณผ ํญ๋ฐœ ๋ฌธ์ž์—ด์„ ์ž…๋ ฅ์œผ๋กœ ๋ฐ›์Šต๋‹ˆ๋‹ค. ๋น ๋ฅธ pop์—ฐ์‚ฐ์„ ์œ„ํ•ด์„œ ์ „์ฒด ๋ฌธ์ž์—ด์€ queue๋กœ ๋ฐ”๊ฟ”์ค๋‹ˆ๋‹ค.

     

    2. ๋ณ€์ˆ˜ ์ดˆ๊ธฐํ™”

    stack = []

    stack์€ ๊ฒฐ๊ณผ๊ฐ’์„ ์ €์žฅํ•  ๋ณ€์ˆ˜์ž…๋‹ˆ๋‹ค.

     

    3. ์Šคํƒ๊ณผ ํ ์‚ฌ์šฉ

    while str:
        ch = str.popleft()
        stack.append(ch)
        if ch == bomb[-1] and stack[-len(bomb):] == bomb:
            for i in range(len(bomb)):
                stack.pop()
    • ์ „์ฒด ๋ฌธ์ž์—ด์˜ ์•ž์—์„œ๋ถ€ํ„ฐ ํ•˜๋‚˜์”ฉ popํ•ด์„œ stack์— ๋„ฃ์Šต๋‹ˆ๋‹ค.
    • popํ•œ ๋ฌธ์ž๊ฐ€ ํญ๋ฐœ ๋ฌธ์ž์—ด์˜ ๋ ๋ฌธ์ž์™€ ๊ฐ™๋‹ค๋ฉด, ํ˜„์žฌ ์Šคํƒ์— ๋“ค์–ด๊ฐ€ ์žˆ๋Š” ๋ฌธ์ž์—ด์˜ ๋์— ํญ๋ฐœ ๋ฌธ์ž์—ด์ด ์žˆ๋Š”์ง€ ๊ฒ€์‚ฌํ•ฉ๋‹ˆ๋‹ค. ํญ๋ฐœ ๋ฌธ์ž์—ด์ด ์žˆ๋‹ค๋ฉด ํญ๋ฐœ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋งŒํผ stack์—์„œ ๋ฌธ์ž๋ฅผ popํ•ฉ๋‹ˆ๋‹ค.
      ์ด๋•Œ, ๋ฆฌ์ŠคํŠธ ์Šฌ๋ผ์ด์‹ฑ(stack = stack[:-len(bomb)])์„ ์ด์šฉํ•˜๋ฉด ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚ฉ๋‹ˆ๋‹ค. ๋ฆฌ์ŠคํŠธ ์Šฌ๋ผ์ด์‹ฑ๋ณด๋‹ค pop ์—ฐ์‚ฐ์ด ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ ํ›จ์”ฌ ๋‚ฎ์Šต๋‹ˆ๋‹ค.
    • ํญ๋ฐœ ๋ฌธ์ž์—ด๊ณผ ๋ ๋ฌธ์ž๋ฅผ ๋น„๊ตํ•˜๋Š” ์ด์œ ๋Š”, ํญ๋ฐœ ํ›„, ํญ๋ฐœ ๋ฌธ์ž์—ด๊ณผ ๊ฐ™์€ ๋ถ€๋ถ„์ด ์ƒˆ๋กญ๊ฒŒ ์ƒ๊ธธ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

     

    4. ์ถœ๋ ฅ

    if not stack:
        print("FRULA")
    else:
        print(''.join(stack))
    • ๋งŒ์•ฝ, stack์— ๋‚จ์•„์žˆ๋Š” ๋ฌธ์ž๊ฐ€ ์—†๋‹ค๋ฉด, ๋ชจ๋“  ๋ฌธ์ž์—ด์ด ํญ๋ฐœํ•œ ๊ฒƒ์ด๋ฏ€๋กœ "FRULA"๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.
    • ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด stack์— ์žˆ๋Š” ๋ฌธ์ž์—ด์„ joinํ•˜์—ฌ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

     

    ๐ŸŒฑ ์ •๋‹ต ์ฝ”๋“œ

    # !/usr/bin/env python
    # -*- coding: utf-8 -*-
    # boj 9935 ๋ฌธ์ž์—ด ํญ๋ฐœ
    
    import sys
    from collections import defaultdict
    from collections import deque
    
    input = sys.stdin.readline
    
    str = deque(list((input().strip())))
    stack = []
    bomb = list(input().strip())
    check = True
    
    while str:
        ch = str.popleft()
        stack.append(ch)
        if ch == bomb[-1] and stack[-len(bomb):] == bomb:
            for i in range(len(bomb)):
                stack.pop()
    
    if not stack:
        print("FRULA")
    else:
        print(''.join(stack))
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€