-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathstrange-printer.py
73 lines (51 loc) · 2.02 KB
/
strange-printer.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from functools import lru_cache
from typing import List, Tuple
class Solution:
def strangePrinter(self, s: str) -> int:
array: List[int] = []
prev = ""
for char in s:
if char != prev:
array.append(ord(char) - ord("a"))
prev = char
@lru_cache(None)
def dp(left: int, right: int) -> int:
if left > right:
return 0
if left == right:
return 1
# Print the first character and stop
result = dp(left + 1, right) + 1
for mid in range(left + 1, right + 1):
# Print the first character until `mid` and stop
if array[left] == array[mid]:
result = min(result, dp(left, mid - 1) + dp(mid + 1, right))
return result
return dp(0, len(array) - 1)
def strangePrinterBruteForce(self, s: str) -> int:
# Easier to work with integers
array = list(ord(letter) - ord("a") for letter in s)
offsets = [1] * len(array)
prev = -1
for pos in reversed(range(len(array))):
if prev == array[pos]:
offsets[pos] = offsets[pos + 1] + 1
prev = array[pos]
@lru_cache(None)
def backtrack(pos: int, print_stack: Tuple[int]) -> int:
if pos == len(array):
return 0
# Regardless if we tried this letter or not try to start anew
stack = list(print_stack)
stack.append(array[pos])
new_print = reuse = backtrack(pos + offsets[pos], tuple(stack)) + 1
stack = list(print_stack)
# If in the stack, uwind the stack until this letter
if array[pos] in stack:
while stack[-1] != array[pos]:
stack.pop()
reuse = backtrack(pos + offsets[pos], tuple(stack))
return min(new_print, reuse)
result = backtrack(0, tuple())
backtrack.cache_clear()
return result