给定一个字符串S,任务是找到字符串s是字符串s另一个不同的子串的字谜全部子。不同的子串意味着子串从不同的索引开始。
例子:
Input: S = “aba”
Output: a a ab ba
Explanation:
Following substrings are anagrams of another substring of the string S:
- “a”: Substring “a” is anagram of the substring “a”(= {S[0]}).
- “a”: Substring “a” is anagram of the substring “a”(= {S[2]}).
- “ab”: Substring “ab” is anagram of the substring “ba”(= {S[1], S[2]}).
- “ba”: Substring “ba” is anagram of the substring “ab”(= {S[0], S[2]}).
Input: S = “abcd”
Output: []
方法:给定的问题可以通过使用 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 )
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。