LeetCode //C - 664. Strange Printer

664. Strange Printer

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.

From: LeetCode
Link: 664. Strange Printer


Solution:

Ideas:
  • Breaking the string into substrings.
  • Calculating the minimum number of turns needed to print each substring.
  • Using character overlaps (same characters) to reduce the total number of turns.
Code:
int min(int a, int b) {
    
    
    return a < b ? a : b;
}

int strangePrinter(char* s) {
    
    
    int n = strlen(s);
    if (n == 0) return 0;

    int dp[100][100];

    for (int i = n - 1; i >= 0; i--) {
    
    
        dp[i][i] = 1;
        for (int j = i + 1; j < n; j++) {
    
    
            dp[i][j] = dp[i + 1][j] + 1;
            for (int k = i + 1; k <= j; k++) {
    
    
                if (s[i] == s[k]) {
    
    
                    int temp = dp[i + 1][k - 1] + dp[k][j];
                    dp[i][j] = min(dp[i][j], temp);
                }
            }
        }
    }

    return dp[0][n - 1];
}