给定一个字符串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: []
方法:给定的问题可以通过使用哈希来解决,方法是存储字符串S的每个子字符串的字母符号,并打印结果子字符串。请按照以下步骤解决给定的问题:
- 初始化一个HashMap,该哈希表存储字符串S的每个子字符串的所有字谜。
- 生成S的所有可能的子字符串,并为每个子字符串说str将子字符串存储在与键作为排序字符串str映射的HashMap中。
- 遍历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 )