Post

๐Ÿน ๊ณตํ†ต ๋ถ€๋ถ„ ๋ฌธ์ž์—ด

1. ๋ฌธ์ œ ๋งํฌ

5582๋ฒˆ: ์‚ฌ๋‹ค๋ฆฌ ํƒ€๊ธฐ


2. ์ฝ”๋“œ

Python3 31120KB 2592ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
str1 = input()
str2 = input()
# str1์ด ๋” ์งง๋„๋ก ์ˆ˜์ •
if len(str1) > len(str2):
    str1, str2 = str2, str1
length = len(str1)

dp = [0] * (length)
for idx in range(length):
    # ํ˜„์žฌ๊นŒ์ง€ ์ฐพ์€ ์ตœ๋Œ€ ๋ฌธ์ž์—ด ๊ธธ์ด๋ถ€ํ„ฐ ํƒ์ƒ‰ 
    start = max(dp)
    for l in range(start, length + 1):
        # str1์˜ ๋ฒ”์œ„๋ฅผ ๋„˜์–ด๊ฐ€๋ฉด break
        if idx + l > length:
            break
        t = str1[idx:idx+l]
        # ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์ด ๋‹ค๋ฅธ ๋ฌธ์ž์—ด์— ํฌํ•จ๋˜์–ด ์žˆ์„ ๋•Œ 
        if t in str2:
            dp[idx] = max(dp[idx], l)
        else:
            break
print(max(dp))


3. ํ•ด์„ค

dp[idx]๋Š” ๋ฌธ์ž์—ด ์‹œ์ž‘์  ์ธ๋ฑ์Šค(idx)๋ถ€ํ„ฐ์˜ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์ผ ๋•Œ ๊ฐ€๋Šฅํ•œ ๊ณตํ†ต ๋ฌธ์ž์—ด์˜ ์ตœ๋Œ€ ๊ธธ์ด์ด๋‹ค.

๋‘ ๋ฌธ์ž์—ด ์ค‘ ๋” ์งง์€ ๋ฌธ์ž์—ด ๊ฐ ์ธ๋ฑ์Šค๋ฅผ ํƒ์ƒ‰ํ•œ๋‹ค. idx๋ถ€ํ„ฐ idx+l(๋ถ€๋ถ„ ๋ฌธ์ž์—ด ๊ธธ์ด)์— ํฌํ•จ๋œ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์ด ๋‹ค๋ฅธ ๋ฌธ์ž์—ด์— ํฌํ•จ๋˜๋Š”์ง€ ํ™•์ธํ•œ ํ›„ ํฌํ•จ๋œ ๊ฒฝ์šฐ์—๋Š” dp๋ฅผ l์˜ ๊ฐ’์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•ด์ค€๋‹ค.

idx+l์ด ์งง์€ ๋ฌธ์ž์—ด ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๋ฉด ๋‹ค์Œ ์œ„์น˜๋ฅผ ํƒ์ƒ‰ํ•œ๋‹ค. ์ด๋•Œ ํ˜„์žฌ๊นŒ์ง€์˜ ๊ณตํ†ต ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์˜ ์ตœ๋Œ€ ๊ธธ์ด๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•œ๋‹ค.(์ตœ๋Œ“๊ฐ’์„ ์ฐพ๋Š” ๊ฒƒ์ด๋ผ ๊ตณ์ด ์ž‘์€ ๊ฒฝ์šฐ๋ฅผ ํƒ์ƒ‰ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.)

This post is licensed under CC BY 4.0 by the author.