File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ // dfs
2
+ class Solution {
3
+ fun longestStrChain (words : Array <String >): Int {
4
+ val wordList = words.toHashSet()
5
+ val dp = HashMap <String , Int >()
6
+
7
+ fun dfs (word : String , len : Int ): Int {
8
+ if (word !in wordList) return 0
9
+ if (" $word :$len " in dp) return dp[" $word :$len " ]!!
10
+
11
+ var res = len
12
+ for (i in 0 until 26 ) {
13
+ for (j in 0 .. word.length) {
14
+ val nextWord = word.substring(0 , j) + (' a' + i) + word.substring(j, word.length)
15
+ res = maxOf(res, dfs(nextWord, len + 1 ))
16
+ }
17
+ }
18
+
19
+ dp[" $word :$len " ] = res
20
+ return res
21
+ }
22
+
23
+ var res = 1
24
+ for (word in wordList) {
25
+ res = maxOf(res, dfs(word, 1 ))
26
+ }
27
+
28
+ return res
29
+ }
30
+ }
31
+
32
+ // dp
33
+ class Solution {
34
+ fun longestStrChain (words : Array <String >): Int {
35
+ words.sortBy { it.length }
36
+ val dp = HashMap <String , Int >()
37
+
38
+ var res = 0
39
+ for (word in words) {
40
+ var cur = 1
41
+ for (i in 0 until word.length) {
42
+ val nextWord = word.substring(0 , i) + word.substring(i + 1 )
43
+ dp[nextWord]?.let {
44
+ cur = maxOf(cur, it + 1 )
45
+ }
46
+ }
47
+
48
+ dp[word] = cur
49
+ res = maxOf(res, cur)
50
+ }
51
+
52
+ return res
53
+ }
54
+ }
You can’t perform that action at this time.
0 commit comments