LeetCode 1048 - Longest String Chain (Medium)

Given a list of words, each word consists of English lowercase letters.

Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2.  For example, "abc" is a predecessor of "abac".

word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2word_2 is a predecessor of word_3, and so on.

Return the longest possible length of a word chain with words chosen from the given list of words.

 

Example 1:

Input: ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: one of the longest word chain is "a","ba","bda","bdca".

 方法:dp

思路:使用一个map来保存每一个word可以形成的最长的长度。

1. 排序words

2. 以"bca"为例,bca可以形成的最长的长度是bc ba ca三个字符可以形成的最长长度+1. 

time complexity: O(nlogn)+O(ns) space complexity O(ns)

class Solution:
    def longestStrChain(self, words: List[str]) -> int:
        if not words or len(words) == 0: return 0 
        
        words.sort(key = lambda x: len(x))
    
        dp = collections.defaultdict(int)
        
        for word in words:
            dp[word] = max(dp[word[:i] + word[i+1:]] + 1 for i in range(len(word)))
        
        return max(dp.values())

 

posted @ 2020-11-06 04:59  Sheanne  阅读(48)  评论(0)    收藏  举报