• 【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
  • 相关阅读:
    图片处理工具类
    基于Redis的在线用户列表解决方案
    Windows安装Mysql5.7.10绿色版
    开启MongoDB客户端访问控制
    在Windows上安装MongoDB
    MongoDB介绍
    常用linux命令
    添加本地jar包到本地的Maven仓库以及在Maven仓库中搜索想要添加的jar包
    Centos6.5安装memcached
    Archive for required library:xxxxx/spring-beans-3.2.4.RELEASE.jar in project XXXXX cannot be read or is not a valid ZIP file
  • 原文地址:https://www.cnblogs.com/seyjs/p/10899689.html
Copyright © 2020-2023  润新知