📌  相关文章
📜  查找作为字符串S 的另一个子串的变位词的所有子串

📅  最后修改于: 2021-09-07 02:22:10             🧑  作者: Mango

给定一个字符串S,任务是找到字符串s是字符串s另一个不同的子串的字谜全部子。不同的子串意味着子串从不同的索引开始。

例子:

方法:给定的问题可以通过使用 Hashing 来解决,方法是存储字符串S的每个子串的变位词并打印结果子串。按照以下步骤解决给定的问题:

  • 初始化一个 HashMap,它存储字符串S的每个子串的所有字谜。
  • 生成 S 的所有可能子字符串,对于每个子字符串,假设str将子字符串存储在与键映射的 HashMap 中作为排序字符串str
  • 遍历HashMap和打印所有与它与每个字符串相关的字符串的数量至少1每个键关联的字符串。

下面是上述方法的实现:

Python3
# Python program for the above approach
  
import collections
  
# Function to find all the substrings
# whose anagram exist as a different
# subtring in S
def findAnagrams(S):
    
    # Stores the lists of anagrams of
    # each substring of S
    Map = collections.defaultdict(list)
      
    # Stores the length of S
    N = len(S)
      
    # Generate all substrings of S
    for i in range(N):
        for j in range(i, N):
              
            # Store the current substring
            # of the string S
            curr = S[i: j + 1]
              
            # Key is the sorted substring
            key = "".join(sorted(curr))
              
            # Add the sorted substring 
            # to the dictionary 
            Map[key].append(curr)
      
    # Store the final result
    result = []
      
    # Iterate over values of dictionary
    for vals in Map.values():
          
        # If length of list > 1
        if len(vals) > 1:
             
            # Print all the strings
            for v in vals:
                  print(v, end =" ")    
  
# Driver Code
  
S = "aba"
findAnagrams(S)


输出:
ab ba a a

时间复杂度: O(N 3 )
辅助空间: O(N 2 )

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live