-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathshortest-way-to-form-string.py
More file actions
31 lines (24 loc) · 963 Bytes
/
shortest-way-to-form-string.py
File metadata and controls
31 lines (24 loc) · 963 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from functools import lru_cache
class Solution:
def shortestWay(self, source: str, target: str) -> int:
@lru_cache(None)
def dp(source_pos: int, target_pos: int) -> int:
if target_pos == len(target):
return int(source_pos != 0)
min_subsequences = float("+inf")
if source[source_pos] != target[target_pos]:
min_subsequences = min(
min_subsequences,
dp((source_pos + 1) % len(source), target_pos)
+ (source_pos + 1) // len(source),
)
else:
min_subsequences = min(
min_subsequences,
dp((source_pos + 1) % len(source), target_pos + 1)
+ (source_pos + 1) // len(source),
)
return min_subsequences
if set(target) - set(source):
return -1
return dp(0, 0)