📌  相关文章
📜  Python|删除k个字符后查找所有可能的子串

📅  最后修改于: 2022-05-13 01:55:02.946000             🧑  作者: Mango

Python|删除k个字符后查找所有可能的子串

给定一个字符串和一个整数 k,编写一个Python程序,在删除 k 个字符后查找给定字符串的所有可能子串。

例子:

Input : geeks, k = 1
Output : {'gees', 'eeks', 'geks', 'geek'}

Input : dog, k = 1
Output : {'do', 'dg', 'og'}


方法#1:朴素的方法
这是在删除 k 个字符后查找所有可能的子字符串的递归天真的方法。首先,我们分别用 0、字符串长度和 0 初始化start、end和 index 变量。我们创建一个临时列表,例如“ temp ”,它一一存储所有输出。我们从temp[]中的第一个索引开始,一个接一个地修复该索引处的元素,并为剩余的索引重复出现。

# Python3 program to Find all combinations 
# of string after deleting k characters
list = []
  
def findCombinations(str, temp, start, end, index, k): 
      
    if (index == k): 
        item = ''
          
        for j in range(k): 
            item += temp[j]
        list.append(item)
        return; 
  
    i = start; 
    while(i <= end and end - i + 1 >= k - index): 
        temp[index] = str[i]
        findCombinations(str, temp, i + 1, 
                        end, index + 1, k); 
        i += 1; 
  
# Driver Code
str = 'geeks'
k = 1
temp = [0]*(len(str)-k)
s, e = 0, len(str)-1
  
findCombinations(str, temp, s, e, 0, len(str)-k)
print(set(list))
输出:
{'eeks', 'gees', 'geks', 'geek'}


方法 #2:使用 Itertools
Python模块 Itertools 提供了一个函数combination() ,它采用字符串和长度来给出字符串的所有可能组合。

# Python3 program to Find all combinations 
# of string after deleting k characters
from itertools import combinations
  
def findCombinations(str, k):
    l = len(str)
    return set([''.join(i) for i in combinations(str, l - k)])
      
# Driver Code
str = 'geeks'
k = 1
print(findCombinations(str, k))
输出:
{'geek', 'eeks', 'geks', 'gees'}