[LeetCode]Strange Printer

题目描述:

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. 从字符串的任意位置开始打印字符,覆盖原始字符

求得到目标串所需的最少打印次数

解题思路:

动态规划(Dynamic Programming)

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[1][size] : 0;
    }
}

 

本文链接:http://bookshadow.com/weblog/2017/08/21/leetcode-strange-printer/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论