There is a strange printer with the following two special properties:
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 place and will cover the original existing characters.
Given a string s, return the minimum number of turns the printer needed to print it.
Example 1:
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'.
Constraints:
1 <= s.length <= 100
s consists of lowercase English letters.
Solutions
Solution 1: Dynamic Programming
We define \(f[i][j]\) as the minimum operations to print \(s[i..j]\), with the initial value \(f[i][j]=\infty\), and the answer is \(f[0][n-1]\), where \(n\) is the length of string \(s\).
Consider \(f[i][j]\), if \(s[i] = s[j]\), we can print \(s[j]\) when print \(s[i]\), so we can ignore \(s[j]\) and continue to print \(s[i+1..j-1]\). If \(s[i] \neq s[j]\), we need to print the substring separately, i.e. \(s[i..k]\) and \(s[k+1..j]\), where \(k \in [i,j)\). So we can have the following transition equation:
We can enumerate \(i\) from large to small and \(j\) from small to large, so that we can ensure that \(f[i][j-1]\), \(f[i][k]\) and \(f[k+1][j]\) have been calculated when we calculate \(f[i][j]\).
The time complexity is \(O(n^3)\) and the space complexity is \(O(n^2)\). Where \(n\) is the length of string \(s\).