problem
O(N*M^2) time
- N: size of array
- M: length of word
class Solution {
fun longestStrChain(words: Array<String>): Int {
words.sortBy { -it.length }
val size = words.size
val table = mutableMapOf<String, Int>()
val sb = StringBuilder()
var answer = 0
for (i in 0 until size) {
val chain = table[words[i]] ?: 0
val length = words[i].length
for (j in 0 until length) {
for (k in 0 until length) {
if (j != k) sb.append(words[i][k])
}
val temp = table[sb.toString()] ?: 0
table[sb.toString()] = maxOf(temp, chain + 1)
answer = maxOf(answer, chain + 1)
sb.clear()
}
}
return answer
}
}
O(N*M) time
class Solution {
fun longestStrChain(words: Array<String>): Int {
words.sortBy { it.length }
val size = words.size
val table = mutableMapOf<String, Int>()
val sb = StringBuilder()
var answer = 0
words.forEach { word ->
table[word] = 1
sb.insert(0, word)
word.forEachIndexed { index, c ->
val deletedChar = sb[index]
sb.deleteCharAt(index)
val prev = table[sb.toString()] ?: 0
val curr = table[word]!!
table[word] = maxOf(prev + 1, curr)
sb.insert(index, deletedChar)
}
answer = maxOf(answer, table[word]!!)
sb.clear()
}
return answer
}
}
without StringBuilder
class Solution {
fun longestStrChain(words: Array<String>): Int {
words.sortBy { it.length }
val size = words.size
val table = mutableMapOf<String, Int>()
var answer = 0
words.forEach { word ->
var chain = 0
for (i in word.indices) {
val prev = word.substring(0, i) + word.substring(i + 1)
val temp = table[prev] ?: 0
chain = maxOf(chain, temp + 1)
}
table[word] = chain
answer = maxOf(answer, chain)
}
return answer
}
}