1
+ # Runtime: 878 ms (Top 47.91%) | Memory: 16.1 MB (Top 47.44%)
1
2
class Solution (object ):
2
3
def strangePrinter (self , s ):
3
4
"""
@@ -19,22 +20,21 @@ def _dp(i, j, background):
19
20
return 1 if background != s [i ] else 0
20
21
elif (i , j , background ) in _m :
21
22
return _m [(i , j , background )]
22
-
23
+
23
24
ans = len (s )
24
-
25
+
25
26
# shrink s[i:j+1] to s[i_:j_+1] according to the background letter
26
27
i_ = i + 1 if s [i ] == background else i
27
28
j_ = j - 1 if s [j ] == background else j
28
-
29
-
29
+
30
30
if s [i_ ] == s [j_ ]:
31
- # case "AxxxA" => best strategy is printing A first
31
+ # case "AxxxA" => best strategy is printing A first
32
32
ans = _dp (i_ + 1 , j_ - 1 , s [i_ ]) + 1
33
33
else :
34
- # otherwise, print first letter, try every possible print length
34
+ # otherwise, print first letter, try every possible print length
35
35
for p in range (i_ , j_ + 1 ):
36
36
# searching is needed only if s[p] == s[i_]
37
- # e.g. s="ABCDEA", print 'A' on s[0:1] is equivalent to s[0:5]
37
+ # e.g. s="ABCDEA"print 'A' on s[0:1] is equivalent to s[0:5]
38
38
if s [p ] != s [i_ ]:
39
39
continue
40
40
l = _dp (i_ , p , s [i_ ])
@@ -43,4 +43,4 @@ def _dp(i, j, background):
43
43
_m [(i , j , background )] = ans
44
44
return ans
45
45
46
- return _dp (0 , len (s ) - 1 , '' )
46
+ return _dp (0 , len (s ) - 1 , '' )
0 commit comments