使用Python的Anagram子串搜索

在本教程中,我们将编写一个程序,该程序从字符串中搜索所有字谜。

看一些例子。

Input:
anagram = "cat"
string = "tacghactcat"
Output:
Anagram at 0
Anagram at 5
Anagram at 7
Anagram at 8

让我们看看如何编写代码。请按照以下步骤编写代码。

算法

1. Initialize two strings.
2. Create a function which returns whether two strings are anagram to each other or not.
3. Iterate through the main string in which we have to search for the anagrams.
   3.1. Check whether substring is an anagram or not using the function that we have defined.
      3.1.1. If True, print the starting index.

如果感觉很难编写,请检查代码。

示例

# importing collections to check for anagrams
import collections
# initializing two strings
anagram = 'cat'
string = 'tacghactcat'
# function to check for anagrams
def is_anagram(string):
   # checking for anagram
   if collections.Counter(anagram) == collections.Counter(string):
      # returning True if anagrams
      return True
   else:
      # returning False if not
      return False
# getting lengths of both strings
anagram_len = len(anagram)
string_len = len(string)
# iterarint through the string
for i in range(string_len - anagram_len + 1):
   # checking for anagram
   if is_anagram(string[i:i+anagram_len]):
      # printing the index
      print(f'Anagram at {i}')

输出结果

如果运行上面的程序,您将得到以下结果。

Anagram at 0
Anagram at 5
Anagram at 7
Anagram at 8

结论

如果您对本教程有疑问,请在评论部分中提及它们。