- Strange Printer Hard
299
38
Favorite
Share There is a strange printer with the following two special requirements:
The printer can only print a sequence of the same character each time. At each turn, the printer can print new characters starting from and ending at any places, and will cover the original existing characters. Given a string consists of lower English letters only, your job is to count the minimum number of turns the printer needed in order to print it.
Example 1: Input: "aaabbb" Output: 2 Explanation: Print "aaa" first and then print "bbb". Example 2: Input: "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'.
思路:动态规划,
- 字符串"a",打印步数1,字符串"ab",打印步数2,如果字符串每个字符都不一样,打印步数即为字符串的长度
- 字符有重复的情况下,字符串"abcdaefg",打印步数为dp[0][4]+dp[5][7],因为a有重复,所以打印dp[0][4]可以省一步,1+dp[1][3],
- 解决思路即为,遍历s,查看是否有k值,使得left=<k<r,s[k+1]==s[left] or s[k]==s[right],
代码:python3
class Solution:
def strangePrinter(self, s: str) -> int:
l=len(s)
self.dp = [[0 for _ in range(l)] for _ in range(l)]
return self.dfs(0,l-1,s)
def dfs(self,l,r,s):
if l>r:return 0
if self.dp[l][r]>0:return self.dp[l][r]
ans = self.dfs(l,r-1,s)+1
for i in range(l,r):
if s[i] == s[r]:
ans=min(ans,self.dfs(l,i,s)+self.dfs(i+1,r-1,s))
self.dp[l][r]=ans
return self.dp[l][r]
if __name__ == '__main__':
print(Solution().strangePrinter("acdeaabbb"))