LeetCode 664: Strange Printer Solution

Master LeetCode problem 664 (Strange Printer), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

664. Strange Printer

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. We will define a 3D dp array where dp[i][j][k] represents the minimum number of turns needed to print the substring s[i:j+1] if we print character s[j] k times at the end. We can then iterate over the string s and update the dp array based on the optimal choices. Finally, the answer will be stored in dp[0][n-1][0] where n is the length of the string s.

Solution Code

class Solution {
    public int strangePrinter(String s) {
        int n = s.length();
        int[][][] dp = new int[n][n][n];
        
        for (int i = n - 1; i >= 0; i--) {
            for (int j = i; j < n; j++) {
                for (int k = 0; k <= j - i; k++) {
                    if (k == 0) {
                        dp[i][j][k] = 1 + (j > i ? dp[i][j - 1][0] : 0);
                    } else {
                        dp[i][j][k] = Integer.MAX_VALUE;
                        for (int m = i; m < j; m++) {
                            if (s.charAt(m) == s.charAt(j)) {
                                dp[i][j][k] = Math.min(dp[i][j][k], dp[i][m][k - 1] + dp[m + 1][j - 1][0]);
                            }
                        }
                    }
                }
            }
        }
        
        return dp[0][n - 1][0];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 664 (Strange Printer)?

This page provides optimized solutions for LeetCode problem 664 (Strange Printer) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 664 (Strange Printer)?

The time complexity for LeetCode 664 (Strange Printer) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 664 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 664 in Java, C++, or Python.

Back to LeetCode Solutions