the longest string chain leetcode-1048
Reference: doudoucao
Subject description:
Given a list of words, where each word by lowercase letters. If we can add a letter anywhere word1 render it word2, then we think word1 word2 is the predecessor. For example, "abc" is "abac" predecessor. Word is a word chain [word_1, word_2, ..., word_k ] sequence composition, k> = 1, which is word_2 WORD_1 predecessor word_2 is word_3 predecessor, and so on. Select the list of words in a given word-word word chain, the chain of words returned from the longest possible length
Note: see this practice in the comments area, it is really too strong
from collections import defaultdict
class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=len)
res = defaultdict(int)
for word in words:
res[word]=max(res[word[:i]+word[i+1:]] for i in range(len(word))) + 1
return max(res.values())