ps | |
---|---|
링크 | programmers.co.kr/… |
출처 | 프로그래머스 |
문제 번호 | 12983 |
문제명 | 단어 퍼즐 |
레벨 | Level 4 |
분류 |
동적 계획법, 문자열 매칭 |
시간복잡도 | O((m+n)k) |
인풋사이즈 | m<=100, n<=20,000, k<=5 |
사용한 언어 | Python |
해결날짜 | 2020/12/25 |
"""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
"""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