原题说明
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”
.
A word chain is a sequence of words [word_1, word_2, …, word_k]
with k >= 1
, where word_1
is a predecessor of word_2
, word_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”.
Note:
1 <= words.length <= 1000
1 <= words[i].length <= 16
words[i]
only consists of English lowercase letters.
解题思路
这道题可以用动态规划的思路来解。
先将给我们的词按长度从小到大排列,然后用一个哈希表记录能从小到大变化到一个词的最大长度。也就是说,key
是一个词,value
是从小到大能变换到这个词的最大长度。
我们按词的长度从小到大遍历所有的词,对于每一个词cur
,遍历这个词的每一个可能的前一个词prev
,若存在在哈希表中,则dp[cur] = max(dp[cur], dp[prev] + 1)
。这也就是我们的状态转移方程。
最后我们查找哈希表中的最大值,就是我们要的答案。
示例代码 (cpp)
1 | class Solution { |
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度: 假设一共有N
个词,词的平均长度是L
,时间复杂度是 O(NlogN + NL^2)
空间复杂度: O(NL)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!