forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1048.go
50 lines (45 loc) · 1.03 KB
/
1048.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
50
type pair struct {
word string
num int
}
func longestStrChain(words []string) int {
mem := make([][]pair, 17)
for i := 0; i <= 16; i++ {
mem[i] = make([]pair, 0)
}
for _, w := range words {
mem[len(w)] = append(mem[len(w)], pair{word:w, num:1})
}
res := 1
for i := 2; i <= 16; i++ {
for j := 0; j < len(mem[i]); j++ {
for k := 0; k < len(mem[i-1]); k++ {
if (isPreString(mem[i-1][k].word, mem[i][j].word)) {
mem[i][j].num = max(mem[i][j].num, mem[i-1][k].num + 1)
}
res = max(res, mem[i][j].num)
}
}
}
return res
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func isPreString(s1, s2 string) bool {
p, n := 0, len(s1)
for i := 0; i < n; i++ {
if s1[i] != s2[i + p] {
p++
if p != 1 {
return false
} else {
i--
}
}
}
return true
}