使用 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.