题目描述：

LeetCode 664. Strange Printer

There is a strange printer with the following two special requirements:

1. The printer can only print a sequence of the same character each time.
2. 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'.

Hint: Length of the given string will not exceed 100.

题目大意：

1. 一次打印某字符重复若干次
2. 从字符串的任意位置开始打印字符，覆盖原始字符

解题思路：

dp[i][j]表示打印下标[i .. j]的子串所需的最少打印次数；记目标串为s

dp[y][x] = min(dp[y][x], dp[y][z-1] + dp[z][x-1] + k)   当s[x-1] != s[z-1]时k取值1，否则k取值0

Java代码：

class Solution {
public int strangePrinter(String s) {
int size = s.length();
int[][] dp = new int[size + 1][size + 1];
for (int x = 1; x <= size; x++) {
for (int y = 1; y <= x; y++) {
dp[y][x] = x - y + 1;
for (int z = y; z < x; z++) {
dp[y][x] = Math.min(dp[y][x], dp[y][z - 1] + dp[z][x - 1] +
(s.charAt(x - 1) != s.charAt(z - 1) ? 1 : 0));
}
}
}
return size > 0 ? dp[size] : 0;
}
}

Pingbacks已关闭。