Skip to content

Instantly share code, notes, and snippets.

@TheGreatJoules
Last active October 22, 2023 08:01
Show Gist options
  • Save TheGreatJoules/627b0a5e15006bfebc2e955614ab0081 to your computer and use it in GitHub Desktop.
Save TheGreatJoules/627b0a5e15006bfebc2e955614ab0081 to your computer and use it in GitHub Desktop.
[Leetcode/438] Find All Anagrams in a String #slidingwindow
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
if (s == null || s.length() == 0) {
return result;
}
if (p == null || p.length() > s.length()) {
return result;
}
int[] s_freq = new int[26];
int[] p_freq = new int[26];
for (int i = 0; i < p.length(); i++) {
s_freq[s.charAt(i) - 'a']++;
p_freq[p.charAt(i) - 'a']++;
}
int left = 0;
int right = p.length();
if (Arrays.equals(s_freq, p_freq)) {
result.add(left);
}
while (right < s.length()) {
s_freq[s.charAt(left++) - 'a']--;
s_freq[s.charAt(right++)- 'a']++;
if (Arrays.equals(s_freq, p_freq)) {
result.add(left);
}
}
return result;
}
}
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