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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

16916๋ฒˆ: ๋ถ€๋ถ„ ๋ฌธ์ž์—ด

์ฒซ์งธ ์ค„์— ๋ฌธ์ž์—ด S, ๋‘˜์งธ ์ค„์— ๋ฌธ์ž์—ด P๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‘ ๋ฌธ์ž์—ด์€ ๋นˆ ๋ฌธ์ž์—ด์ด ์•„๋‹ˆ๋ฉฐ, ๊ธธ์ด๋Š” 100๋งŒ์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค. ๋˜, ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ๋ฌธ์ž์—ด S, P๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ P๊ฐ€ S์˜ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์ธ์ง€ ํŒ๋‹จํ•˜์—ฌ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ๋‘ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋Š” 100๋งŒ ๋ฏธ๋งŒ์ด๋ฏ€๋กœ ๋‹จ์ˆœํžˆ `print(int(p in s))`์™€ ๊ฐ™์ด ํ’€๊ฒŒ ๋˜๋ฉด ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. ๋”ฐ๋ผ์„œ `KMP ์•Œ๊ณ ๋ฆฌ์ฆ˜`์„ ํ™œ์šฉํ•˜์—ฌ ํ•„์š” ์—†๋Š” ๊ณณ์˜ ํƒ์ƒ‰์„ ๊ฑด๋„ˆ๋›ฐ๋„๋ก ํ•˜์—ฌ์•ผ ์‹œ๊ฐ„ ๋‚ด์— ํ†ต๊ณผํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ๋Š” `KMP ์•Œ๊ณ ๋ฆฌ์ฆ˜`์„ ์ดํ•ดํ•˜๊ณ  ๊ตฌํ˜„ํ•˜๋ฉด ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

def make_table():
    length = len(p)
    table = [0] * len(p)
    j = 0
    for i in range(1, length):
        while j > 0 and p[i] != p[j]:
            j = table[j - 1]
        if p[i] == p[j]:
            j += 1
            table[i] = j
    return table


def kmp():
    table = make_table()
    j = 0
    for i in range(len(s)):
        while j > 0 and s[i] != p[j]:
            j = table[j - 1]
        if s[i] == p[j]:
            if j == len(p) - 1:
                return True
            else:
                j += 1
    return False


if __name__ == "__main__":
    s = input()
    p = input()
    print(1 if kmp() else 0)

 

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