在 Python 中删除 k 个字符后查找所有可能的子字符串
pythonserver side programmingprogramming更新于 2025/10/11 9:16:17
我们得到一个字符串。所需的任务是从字符串中取出一个字母并打印字符串中剩余的字母。我们必须对字符串的每个字母都这样做。
使用循环和范围
这是一种基本的编程方法,我们首先列出所需的参数,例如声明字符串、为起始和终止位置创建变量并为每个字母创建一个临时占位符。我们创建一个函数,它将遍历每个字母并创建一个剩余字母的字符串。
示例
list = [] def letterCombinations(s, t, start, end, index, k): if (index == k): elem = '' for j in range(k): elem += t[j] list.append(elem) return i = start while (i <= end 并且 end - i + 1 >= k - index): temp[index] = s[i] letterCombinations(s, t, i + 1, end, index + 1, k) i += 1 stringA = 'Apple' k = 1 temp = [0] * (len(stringA) - k) start = 0 end = len(stringA) - 1 letterCombinations(stringA, temp, start, end, 0, len(stringA) - k) print(set(list))
输出
运行上述代码得到以下结果 −
{'pple', 'Aple', 'Appl', 'Appe'}
使用 itertools
在这种方法中,我们使用 itertools 模块,该模块有一个名为 combinations 的函数。在我们从给定的字符串中删除一个字母后,该模块负责创建所有可能的字母组合。
示例
from itertools import combinations stringA = 'Apple' k = 1 # using combinations res = set([''.join(i) for i in combinations(stringA, len(stringA) - k)]) print(res)
输出
运行上述代码得到以下结果 −
{'Appl', 'Aple', 'Appe', 'pple'}
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

