-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths1048_longest_string_chain.go
More file actions
53 lines (42 loc) · 1.19 KB
/
s1048_longest_string_chain.go
File metadata and controls
53 lines (42 loc) · 1.19 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
/*
https://leetcode.com/problems/longest-string-chain/
You are given an array of words where each word consists of lowercase English
letters.
wordA is a predecessor of wordB if and only if we can insert exactly one letter
anywhere
in wordA without changing the order of the other characters to make it equal to
wordB.
For example, "abc" is a predecessor of "abac", while "cba" is not a
predecessor of "bcad".
A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1,
where word1
is a predecessor of word2, word2 is a predecessor of word3, and so on. A single
word is
trivially a word chain with k == 1.
Return the length of the longest possible word chain with words chosen from the
given list
of words.
*/
package solutions
import (
"sort"
)
func longestStrChain(words []string) int {
sort.Slice(words, func(i, j int) bool {
return len(words[i]) < len(words[j])
})
dp := make(map[string]int)
res := 1
for _, w := range words {
currLen := 1
for i := 0; i < len(w); i++ {
temp := w
temp = temp[:i] + temp[i+1:]
prevLen := dp[temp]
currLen = Maximum(currLen, prevLen+1)
}
dp[w] = currLen
res = Maximum(res, currLen)
}
return res
}