664. Strange Printer

来源:互联网 发布:凌波城静脉不动的算法 编辑:程序博客网 时间:2024/06/04 17:53

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: 2Explanation: Print "aaa" first and then print "bbb".

Example 2:

Input: "aba"Output: 2Explanation: 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.


思路: * 对于每个string,考虑最后XXXXX,分成2部分
 * 如果第一部分的最后与第二部分的最后一样(为什么考虑最后一位呢?就是为什么是j-1和i+d呢?因为我们现在求得是i-i+d范围,要么是后半部分开始的j,要么是i+d,试想如果j和j+1是一样的,那么就会在j的下一个循环被考虑到,因此我们只需要考虑后半部分的结尾就可以,当然为了以防万一也可以吧j和j+1相等的情况也写进代码)
 * 那在print第一部分的最后的时候就可以吧第二部分的最后也顺带处理掉了
 * 这时候就要减一
 * 
 * 如果不能分成2部分,比如aaaaaa,在减一的时候就处理掉了
 * 
 * 应该是先计算间隔,不清楚可以先写递归


class Solution {    public int strangePrinter(String s) {    int n = s.length();    if(n == 0)return 0;    int[][] dp = new int[n][n];    for(int i=0; i<n; i++)dp[i][i] = 1;    char[] cs = s.toCharArray();        for(int d=1; d<n; d++) {    for(int i=0; i+d<n; i++) {    dp[i][i+d] = d+1;    for(int j=i+1; j<=i+d; j++) {    int t = dp[i][j-1] + dp[j][i+d];    if(cs[j-1] == cs[i+d])t--;    dp[i][i+d] = Math.min(dp[i][i+d], t);    }    }    }        return dp[0][n-1];    }



原创粉丝点击