-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
49 lines (38 loc) · 775 Bytes
/
main.go
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
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(minExtraChar("leetscode", []string{"leet", "code", "leetcode"}))
}
func minExtraChar(s string, dictionary []string) int {
mp := make(map[string]bool)
for _, v := range dictionary {
mp[v] = true
}
return runner(s, mp, 0, make(map[info]int))
}
type info struct {
s string
k int
}
func runner(s string, mp map[string]bool, k int, memo map[info]int) int {
if len(s) == 0 {
return k
}
key := info{s, k}
if val, ok := memo[key]; ok {
return val
}
result := math.MaxInt32
for i := 0; i < len(s); i++ {
if mp[s[0:i+1]] {
val := runner(s[i+1:], mp, k, memo)
result = min(result, val)
}
}
result = min(result, runner(s[1:], mp, k+1, memo))
memo[key] = result
return result
}