664. Strange Printer

Question

We 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.

Solution:

  • Method 1: dp O(N^3) Imgur
    • the hint of 100 means the O(N^3), 500 - 1000 always means O(N^2)
    • how can we use the dp? We need to combine recursion and dp together.
      • Recursion: turn(s, i, j) get the minimum step to print s from index i to j.
      • fallback: turn(s, i, j) = turn(s, i, j - 1) + 1;
      • Optimization: dp[i][j] = dp[i][k] + dp[k + 1][j - 1] where k >= i && k < j and we need char at k euqals char at j.
        • since charAt(k) == charAt(j), we can print their value as that char duing the period of dp[i][k].
            class Solution {
            private int[][] dp;
            public int strangePrinter(String s) {
            int len = s.length();
            dp = new int[len + 1][len + 1];
            return turn(s, 1, len);
            }
            private int turn(String s, int i, int j){
            if(i > j) return 0; //empty string.
            else if(dp[i][j] > 0) return dp[i][j]; //Cached
            else{
            //Give the fall back.
            dp[i][j] = turn(s, i, j - 1) + 1;
            for(int k = i; k < j; k++){
                if(s.charAt(j - 1) == s.charAt(k - 1))
                    dp[i][j] = Math.min(turn(s, i, k) + turn(s, k + 1, j - 1), dp[i][j]);
            }
            return dp[i][j];
            }
            }
            }
          

Reference

  1. 花花酱 LeetCode 664. Strange Printer