We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent c5ed3d6 commit 53e48e5Copy full SHA for 53e48e5
0601-0700/0664_strange_printer.rb
@@ -0,0 +1,24 @@
1
+# @param {String} s
2
+# @return {Integer}
3
+def strange_printer(s)
4
+ dp = Array.new(s.length) { Array.new(s.length, Float::INFINITY) }
5
+
6
+ (s.length-1).downto(0) { |i|
7
+ dp[i][i] = 1
8
+ (i+1...s.length).each { |j|
9
+ # assume s[i..j] like a...a
10
+ # we always need to print the first character 'a',
11
+ # the optimize way is we print all 'a' from i to j,
12
+ # hence the last character is also printed if they are the same
13
+ if s[j] == s[i]
14
+ dp[i][j] = dp[i][j-1]
15
+ else
16
+ (i+1..j).each { |k|
17
+ dp[i][j] = [dp[i][j], dp[i][k-1] + dp[k][j]].min
18
+ }
19
+ end
20
21
22
23
+ dp[0][s.length-1]
24
+end
0 commit comments