Skip to content

Instantly share code, notes, and snippets.

@TheGreatJoules
Last active October 19, 2023 06:30
Show Gist options
  • Save TheGreatJoules/406d628de7dda3ccce732ef127a39a71 to your computer and use it in GitHub Desktop.
Save TheGreatJoules/406d628de7dda3ccce732ef127a39a71 to your computer and use it in GitHub Desktop.
[Leetcode/438A/Python] Find All Anagrams in a String #python #slidingwindow
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
result = []
if len(s) < len(p):
return result
s_freq = [0 for _ in range(26)]
p_freq = [0 for _ in range(26)]
for i in range(len(p)):
s_freq[ord(s[i]) - ord('a')] += 1
p_freq[ord(p[i]) - ord('a')] += 1
if s_freq == p_freq:
result.append(0)
for i in range(len(p), len(s)):
s_freq[ord(s[i - len(p)]) - ord('a')] -= 1
s_freq[ord(s[i]) - ord('a')] += 1
if s_freq == p_freq:
result.append(i - len(p) + 1)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment