1
# Runtime: 878 ms (Top 47.91%) | Memory: 16.1 MB (Top 47.44%)3
def strangePrinter(self, s):8
# remove duplicate letters from s.11
if len(tmp) == 0 or tmp[-1] != c:17
def _dp(i, j, background):21
return 1 if background != s[i] else 022
elif (i, j, background) in _m:23
return _m[(i, j, background)]27
# shrink s[i:j+1] to s[i_:j_+1] according to the background letter28
i_ = i + 1 if s[i] == background else i29
j_ = j - 1 if s[j] == background else j32
# case "AxxxA" => best strategy is printing A first33
ans = _dp(i_ + 1, j_ - 1, s[i_]) + 135
# otherwise, print first letter, try every possible print length36
for p in range(i_, j_ + 1):37
# searching is needed only if s[p] == s[i_]38
# e.g. s="ABCDEA"print 'A' on s[0:1] is equivalent to s[0:5]42
r = _dp(p + 1, j_, background)43
ans = min(ans, l + r + 1)44
_m[(i, j, background)] = ans47
return _dp(0, len(s) - 1, "")