-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC0447.py
34 lines (27 loc) · 1.22 KB
/
LC0447.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
class Solution:
def strangePrinter(self, s: str) -> int:
# Preprocess the string to remove consecutive duplicate characters
s = "".join(char for char, _ in itertools.groupby(s))
memo = {}
def _minimum_turns(start, end) -> int:
# Base case: empty string requires 0 turns
if start > end:
return 0
# If result is memoized, return it
if (start, end) in memo:
return memo[(start, end)]
# Initialize with worst case: print each character separately
min_turns = 1 + _minimum_turns(start + 1, end)
# Try to optimize by finding matching characters
for k in range(start + 1, end + 1):
if s[k] == s[start]:
# If match found, try splitting the problem
turns_with_match = _minimum_turns(
start, k - 1
) + _minimum_turns(k + 1, end)
min_turns = min(min_turns, turns_with_match)
# Memoize and return the result
memo[(start, end)] = min_turns
return min_turns
# Start the recursive process
return _minimum_turns(0, len(s) - 1)