【leetcode】1048. Longest String Chain
题目如下:
Given a list of words, each word consists of English lowercase letters.
Let's say
word1
is a predecessor ofword2
if and only if we can add exactly one letter anywhere inword1
to make it equal toword2
. For example,"abc"
is a predecessor of"abac"
.A word chain is a sequence of words
[word_1, word_2, ..., word_k]
withk >= 1
, whereword_1
is a predecessor ofword_2
,word_2
is a predecessor ofword_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.
解题思路:典型的动态规划的场景。设dp[i]为word[i]的单词链最长距离,如果word[i]是word[j]的predecessor,那么有dp[i] = max(dp[i], dp[j] + 1)。至于如何判断word[i]是否是word[j]的predecessor?对两个单词进行逐位比较,只允许有某一个的字符不一样。
代码如下:
class Solution(object): def longestStrChain(self, words): """ :type words: List[str] :rtype: int """ def isPredecessor(s1,s2): add = False s1_inx = 0 s2_inx = 0 while s1_inx < len(s1) and s2_inx < len(s2): if s1[s1_inx] == s2[s2_inx]: s1_inx += 1 s2_inx += 1 elif add == False: s2_inx += 1 add = True else: return False return True words.sort(cmp=lambda x,y:len(x) - len(y)) dp = [1] * len(words) res = 1 for i in range(len(words)): for j in range(0,i): if len(words[i]) == len(words[j]): break elif len(words[i]) - 1 > len(words[j]): continue else: if isPredecessor(words[j],words[i]): dp[i] = max(dp[i],dp[j]+1) res = max(res,dp[i]) #print words #print dp return res