Leetcode 1048. Longest String Chain

Wencao Yang
1 min readMay 31, 2021

--

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.

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

--

--

Wencao Yang
Wencao Yang

Written by Wencao Yang

Data Scientist & Physics PhD

No responses yet