使用 Python 进行字谜子串搜索


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

看一些例子。

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

结论

如果你对本教程有任何疑问,请在评论区提出。

更新于:2019-11-04

194 次观看

开启您的 职业生涯

完成课程通过认证

开始
广告
© . All rights reserved.