Skip to content

Commit 44acf5a

Browse files
committed
Add solution #664
1 parent 4555ee2 commit 44acf5a

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,7 @@
499499
659|[Split Array into Consecutive Subsequences](./0659-split-array-into-consecutive-subsequences.js)|Medium|
500500
661|[Image Smoother](./0661-image-smoother.js)|Easy|
501501
662|[Maximum Width of Binary Tree](./0662-maximum-width-of-binary-tree.js)|Medium|
502+
664|[Strange Printer](./0664-strange-printer.js)|Hard|
502503
680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy|
503504
684|[Redundant Connection](./0684-redundant-connection.js)|Medium|
504505
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|

solutions/0664-strange-printer.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 664. Strange Printer
3+
* https://leetcode.com/problems/strange-printer/
4+
* Difficulty: Hard
5+
*
6+
* There is a strange printer with the following two special properties:
7+
* - The printer can only print a sequence of the same character each time.
8+
* - At each turn, the printer can print new characters starting from and ending at any place and
9+
* will cover the original existing characters.
10+
*
11+
* Given a string s, return the minimum number of turns the printer needed to print it.
12+
*/
13+
14+
/**
15+
* @param {string} s
16+
* @return {number}
17+
*/
18+
var strangePrinter = function(s) {
19+
const n = s.length;
20+
const dp = new Array(n).fill().map(() => new Array(n).fill(0));
21+
22+
for (let i = n - 1; i >= 0; i--) {
23+
dp[i][i] = 1;
24+
for (let j = i + 1; j < n; j++) {
25+
dp[i][j] = dp[i][j - 1] + 1;
26+
for (let k = i; k < j; k++) {
27+
if (s[k] === s[j]) {
28+
dp[i][j] = Math.min(dp[i][j], dp[i][k] + (k + 1 <= j - 1 ? dp[k + 1][j - 1] : 0));
29+
}
30+
}
31+
}
32+
}
33+
34+
return dp[0][n - 1];
35+
};

0 commit comments

Comments
 (0)