Skip to content

Commit 8e7c86b

Browse files
add 1048
1 parent 5ee93a8 commit 8e7c86b

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

contest/src/main/java/com/github/contest/Execute.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.github.contest
22

33

4-
import com.github.contest.array.sortArrayByParityIIAlternativeSolution
4+
import com.github.contest.dp.longestStrChain
55
import java.util.TreeMap
66

77

@@ -11,7 +11,7 @@ import java.util.TreeMap
1111

1212
fun main() {
1313

14-
sortArrayByParityIIAlternativeSolution(intArrayOf(4, 2, 5, 7)).also { it.printArray() }
14+
longestStrChain(arrayOf("a", "b", "ba", "bca", "bda", "bdca")).also { println(it) }
1515

1616
}
1717

contest/src/main/java/com/github/contest/dp/DpLeetcode.kt

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,3 +373,25 @@ fun longestCommonSubsequence(text1: String, text2: String): Int {
373373

374374
return dp[n][m]
375375
}
376+
377+
/**
378+
* 1048. Longest String Chain
379+
*/
380+
381+
fun longestStrChain(words: Array<String>): Int {
382+
val sortedWords = words.sortedBy { it.length }
383+
val dp = mutableMapOf<String, Int>()
384+
var longestChain = 0
385+
386+
for (word in sortedWords) {
387+
var currentChain = 1
388+
for (i in word.indices) {
389+
val predecessor = word.removeRange(i, i + 1)
390+
currentChain = maxOf(currentChain, dp.getOrDefault(predecessor, 0) + 1)
391+
}
392+
dp[word] = currentChain
393+
longestChain = maxOf(longestChain, currentChain)
394+
}
395+
396+
return longestChain
397+
}

0 commit comments

Comments
 (0)