Skip to content

Commit 53e48e5

Browse files
committed
0664
1 parent c5ed3d6 commit 53e48e5

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

0601-0700/0664_strange_printer.rb

+24
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)