Leetcode 1048. Longest String Chain
You are given an array of
words
where each word consists of lowercase English letters.
wordA
is a predecessor ofwordB
if and only if we can insert exactly one letter anywhere inwordA
without changing the order of the other characters to make it equal towordB
.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]
withk >= 1
, whereword1
is a predecessor ofword2
,word2
is a predecessor ofword3
, and so on. A single word is trivially a word chain withk == 1
.Return the length of the longest possible word chain with words chosen from the given list of
words
.
solution: dfs with memorization
python3 solution
def longestStrChain(self, words: List[str]) -> int:
word_set = set(words) memo = dict() def dfs(word): if word in memo: return memo[word] max_len = 1 for i in range(len(word)): new_word = word[:i] + word[i + 1:] if new_word in word_set: max_len = max(max_len, 1 + dfs(new_word)) memo[word] = max_len
return max_len ans = 1 for word in words: ans = max(ans, dfs(word)) return ans