-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path664-StrangePrinter.go
More file actions
88 lines (78 loc) · 2.6 KB
/
664-StrangePrinter.go
File metadata and controls
88 lines (78 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
// 664. Strange Printer
// There is a strange printer with the following two special properties:
// The printer can only print a sequence of the same character each time.
// At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
// Given a string s, return the minimum number of turns the printer needed to print it.
// Example 1:
// Input: s = "aaabbb"
// Output: 2
// Explanation: Print "aaa" first and then print "bbb".
// Example 2:
// Input: s = "aba"
// Output: 2
// Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
// Constraints:
// 1 <= s.length <= 100
// s consists of lowercase English letters.
import "fmt"
func strangePrinter(s string) int {
n := len(s)
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
min := func (x, y int) int { if x < y { return x; }; return y; }
for i := n - 1; i > -1; i-- {
dp[i][i] = 1
for j := i + 1; j < n; j++ {
dp[i][j] = dp[i][j-1] + 1
for k := i; k < j; k++ {
if s[k] == s[j] {
if k+1 <= j-1 {
dp[i][j] = min(dp[i][j], dp[i][k]+dp[k+1][j-1])
} else {
dp[i][j] = min(dp[i][j], dp[i][k])
}
}
}
}
}
return dp[0][n-1]
}
func strangePrinter1(s string) int {
n, inf := len(s), 1 << 32 - 1
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
min := func (x, y int) int { if x < y { return x; }; return y; }
for i := n-1; i >= 0; i-- {
dp[i][i]=1
for j:= i+1; j < n; j++ {
if s[i] == s[j] {
dp[i][j] = dp[i][j-1]
} else {
dp[i][j] = inf
for k := i; k < j; k++ {
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j])
}
}
}
}
return dp[0][n-1]
}
func main() {
// Example 1:
// Input: s = "aaabbb"
// Output: 2
// Explanation: Print "aaa" first and then print "bbb".
fmt.Println(strangePrinter("aaabbb")) // 2
// Example 2:
// Input: s = "aba"
// Output: 2
// Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
fmt.Println(strangePrinter("aba")) // 2
fmt.Println(strangePrinter1("aaabbb")) // 2
fmt.Println(strangePrinter1("aba")) // 2
}