【leetcode】1048. Longest String Chain


題目如下:

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". 

 

Note:

  1. 1 <= words.length <= 1000
  2. 1 <= words[i].length <= 16
  3. 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM