Strange Printer in C++


Suppose there is a strange printer It has some requirements −

  • The printer can print only a sequence of the same character each time.
  • In each turn, the printer can print new characters starting from and ending at any places, and will cover the original existing characters.

So if we have a string consists of lower letters, our task is to count the minimum number of turns the printer needed in order to print it.

So if the input is like “aaabba”, then it will take 2 turns, first prints aaaaa then b’s by replacing the characters.

To solve this, we will follow these steps −

  • n := size of s
  • if n is same as 0, then: return 0
  • Define one 2D array dp of order n x n, fill this with infinity
  • for initialize l := 1, when l <= n, update (increase l by 1), do −
    • for initialize i := 0, j := l - 1, when j < n, update (increase i by 1), (increase j by 1), do −
      • if l is same as 1, then: dp[i, j] := 1
    • otherwise when l is same as 2, then −
      • dp[i, j] := 1 when s[i] is same as s[j] otherwise 2
    • Otherwise
      • for initialize k := i, when k <j, update (increase k by 1), do −
        • temp := dp[i, k] + dp[k + 1, j]
        • dp[i, j] := minimum of dp[i, j] and (temp – 1 when s[k] is same as s[j] otherwise temp.
  • return dp[0, n - 1]

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
class Solution {
public:
   int strangePrinter(string s) {
      int n = s.size();
      if(n == 0) return 0;
      vector < vector <int> > dp(n, vector <int>(n, INF));
      for(int l = 1; l <= n; l++){
      for(int i = 0, j = l - 1; j < n; i++, j++){
         if(l == 1){
            dp[i][j] = 1;
            }else if(l == 2){
               dp[i][j] = s[i] == s[j] ? 1 : 2;
            }else{
               for(int k = i; k < j; k++){
                  int temp = dp[i][k] + dp[k + 1][j];
                  dp[i][j] = min(dp[i][j], s[k] == s[j] ? temp - 1: temp);
               }
            }
         }
      }
      return dp[0][n - 1];
   }
};
main(){
   Solution ob;
   cout << (ob.strangePrinter("aaabba"));
}

Input

“2*”

Output

2

Updated on: 01-Jun-2020

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements