Input: s = “aaabbb”
Output: 2
Explanation: Print “aaa” first and then print “bbb”.
Example 2:
Input: s = “aba”
Output: 2
Explanation: Print “aaa” first and then print “b” from the second place of the string, which will cover the existing character ‘a’.
classSolution: defstrangePrinter(self, s: str) -> int: min2 = lambda a, b: a if a <= b else b ss: list[int] = [] # `ss` is `s` without consecutive identical characters. occurs: list[list[int]] = [[] for _ inrange(26)] # occurs[char]: char's occurrences in ss prev = '' for c in s: if c == prev: continue val = ord(c) - 97 occurs[val].append(len(ss)) ss.append(val) prev = c
n = len(ss) dp = [[0] * n for _ inrange(n)] for i inrange(n): dp[i][i] = 1
for size inrange(2, n + 1): for i inrange(n - size + 1): j = i + size - 1 dp[i][j] = 1 + dp[i+1][j] if ss[j] == ss[i]: dp[i][j] = min2(dp[i][j], dp[i][j-1])
occ = occurs[ss[i]] for k in occ[bisect_left(occ, i)+1:]: if k >= j: break dp[i][j] = min2(dp[i][j], dp[i][k-1] + dp[k+1][j])
from bisect import bisect_left from functools import cache
classSolution: defstrangePrinter(self, s: str) -> int: min2 = lambda a, b: a if a <= b else b ss: list[int] = [] # `ss` is `s` without consecutive identical characters. occurs: list[list[int]] = [[] for _ inrange(26)] # occurs[char]: char's occurrences in ss prev = '' for c in s: if c == prev: continue val = ord(c) - 97 occurs[val].append(len(ss)) ss.append(val) prev = c
@cache defdfs(l: int, r: int) -> int: if l >= r: return0 elif l == r - 1: return1
min_cnt = 1 + dfs(l+1, r)
occ = occurs[ss[l]] for k in occ[bisect_left(occ, l)+1:]: if k >= r: break min_cnt = min2(min_cnt, dfs(l, k) + dfs(k+1, r))