목차

단어 퍼즐

ps
링크programmers.co.kr/…
출처프로그래머스
문제 번호12983
문제명단어 퍼즐
레벨Level 4
분류

동적 계획법, 문자열 매칭

시간복잡도O((m+n)k)
인풋사이즈m<=100, n<=20,000, k<=5
사용한 언어Python
해결날짜2020/12/25

풀이

코드

코드 1 - 일반적 스트링 매칭

"""Solution code for "Programmers 12983. 단어 퍼즐".

- Problem link: https://programmers.co.kr/learn/courses/30/lessons/12983
- Solution link: http://www.teferi.net/ps/problems/programmers/12983
"""

INF = float('inf')


def solution(strs, t):
    strs_set = set(strs)
    dp = [0] * (len(t) + 1)
    for i in range(1, len(t) + 1):
        dp[i] = min((dp[prev] + 1
                     for prev in range(max(0, i - 5), i)
                     if t[prev:i] in strs_set),
                    default=INF)
    return dp[-1] if dp[-1] != INF else -1

코드 2 - Rabin fingerprint

"""Solution code for "Programmers 12983. 단어 퍼즐".

Using Rabin-fingerprint for string matching.
- Problem link: https://programmers.co.kr/learn/courses/30/lessons/12983
- Solution link: http://www.teferi.net/ps/problems/programmers/12983
"""

from teflib import string

INF = float('inf')


def solution(strs, t):
    p_hashes = set(string.fingerprint(s) for s in strs)
    t_hashes = [list(string.gen_fingerprints(t, l)) for l in range(1, 6)]
    dp = [0] * (len(t) + 1)
    for i in range(1, len(t) + 1):
        dp[i] = min((dp[i - x] + 1
                     for x in range(1, min(5, i) + 1)
                     if t_hashes[x - 1][i - x] in p_hashes),
                    default=INF)
    return dp[-1] if dp[-1] != INF else -1