Skip to content

Instantly share code, notes, and snippets.

@Desolve
Created May 24, 2020 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Desolve/843bd02ae84e41fa25f51d938e2ddd3b to your computer and use it in GitHub Desktop.
Save Desolve/843bd02ae84e41fa25f51d938e2ddd3b to your computer and use it in GitHub Desktop.
0438 Find All Anagrams in a String
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
res = []
if not s or not p or len(s) < len(p): return res
pHash = {}
for c in 'abcdefghijklmnopqrstuvwxyz':
pHash[c] = 0
for c in p:
pHash[c] += 1
cnt, l, r = len(p), 0, 0
while r < len(s):
if pHash[s[r]] > 0: cnt -= 1
pHash[s[r]] -= 1
r += 1
if cnt == 0: res.append(l)
if r - l == len(p):
if pHash[s[l]] >= 0: cnt += 1
pHash[s[l]] += 1
l += 1
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment