Created
August 29, 2019 16:02
-
-
Save priyankvex/226307190e92b655338cc56a882a0105 to your computer and use it in GitHub Desktop.
Find the anagram substring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import Counter, defaultdict | |
class Solution(object): | |
def solve(self, s1, s2): | |
s1 = list(s1) | |
s2 = list(s2) | |
map1 = Counter(s1) | |
n = len(s1) | |
map2 = defaultdict(int) | |
for i in range(0, n): | |
map2[s2[i]] = map2[s2[i]] + 1 | |
are_anagrams = self.check_anagrams(map1, map2) | |
if are_anagrams: | |
return "".join(s2) | |
for i, ch in enumerate(s2): | |
if i < n: | |
continue | |
are_anagrams = self.check_anagrams(map1, map2) | |
if are_anagrams: | |
return "".join(s2[i-n:i]) | |
# remove what's out of the window | |
index_to_remove = i - n | |
character_to_remove = s2[index_to_remove] | |
map2[character_to_remove] = map2[character_to_remove] - 1 | |
if map2[character_to_remove] == 0: | |
map2.pop(character_to_remove) | |
# insert the new character | |
map2[ch] = map2[ch] + 1 | |
return None | |
def check_anagrams(self, map1, map2): | |
n = len(map1) | |
m = len(map2) | |
if n != m: | |
return False | |
for k, v in map1.items(): | |
if v != map2[k]: | |
return False | |
return True | |
if __name__ == "__main__": | |
s1 = "hyzx" | |
s2 = "abcdegfhxzypop" | |
ans = Solution().solve(s1, s2) | |
print(ans) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment