假设我们有一个有效单词的列表,也有一个字符串s,我们必须找到最长的递减单词链的长度,这些单词可以通过以s开头并删除单个字母来生成,并且仍然是有效单词来生成。
因此,如果输入像单词= [“ lii”,“ limit”,“ limi”,“ li”,“ coffee”,“ jug”,“ pool”,“ type”] s =“ limit”,则输出将是4,正如我们可以做的那样,从单词“ limit”,“ limit”->“ limi”->“ lii”->“ li”开始。
为了解决这个问题,我们将按照以下步骤
定义一个功能solve()
。这将需要单词,s
max_num:= 0
对于每个我说的话
对于范围0到s大小的j,执行
max_num:=最大值为1 + solve(单词,s [从索引0到j-1]连接s [从索引j +1到结尾])和max_num
如果我与s相同,则
返回max_num
class Solution: def solve(self, words, s): max_num = 0 for i in words: if i == s: for j in range(len(s)): max_num = max(1 + self.solve(words, s[:j] + s[j + 1 :]), max_num) return max_num ob = Solution()words = ["lii", "limit", "limi", "li", "coffee", "jug", "pool", "type"] s = "limit" print(ob.solve(words, s))
["lii", "limit", "limi", "li", "coffee", "jug", "pool", "type"],"limit"
输出结果
4