用 Python 编写程序来查找最长递减词链的长度?
pythonserver side programmingprogramming更新于 2026/2/16 14:36:17
假设我们有一个有效单词列表,还有一个字符串 s,我们必须找到从 s 开始并删除单个字母并仍然生成有效单词的最长递减词链的长度。
因此,如果输入为 words = ["lii", "limit", "limi", "li", "coffee", "jug", "pool", "type"] s = "limit",则输出将为 4,因为我们可以生成从单词 "limit" 开始的链,"limit" ->"limi" -> "lii" -> "li"。
为了解决这个问题,我们将遵循以下步骤
定义一个函数solve()。这将获取单词 s
max_num := 0
对于单词中的每个 i,执行
如果 i 与 s 相同,则
对于范围从 0 到 s 大小的 j,执行
max_num := 最大值 1 + 解决(单词,s[从索引 0 到 j-1] 连接 s[从索引 j + 1 到结束])和 max_num
返回 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
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/
打印
下一节:用 Python 编写程序来查找一对 (i, j),其中 nums[i] + nums[j] + (i -j) 最大化? ❯❮ 上一节:用 Python 编写程序,找出爬上楼梯顶部所需的最小成本?

