Find All Anagrams in a String
LeetCode https://leetcode.cn/problems/find-all-anagrams-in-a-string/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<>();
if (s == null || p == null) {
return res;
}
if (s.length() == 0 || p.length() > s.length()) {
return res;
}
Map<Character, Integer> freq = new HashMap<>();
for (int i = 0; i < p.length(); i++) {
freq.put(p.charAt(i),
freq.getOrDefault(p.charAt(i), 0) + 1);
} // end count frequency
int matched = 0;
int windowSize = p.length();
for (int i = 0; i < s.length(); i++) {
char newChar = s.charAt(i);
Integer newFreq = freq.get(newChar);
if (newFreq != null) {
freq.put(newChar, --newFreq);
if (newFreq == 0) {
matched++;
}
}
if (i >= windowSize) {
char oldChar = s.charAt(i - windowSize);
Integer oldFreq = freq.get(oldChar);
if (oldFreq != null) {
freq.put(oldChar, ++oldFreq);
if (oldFreq == 1) {
matched--;
}
}
}
if (matched == freq.size()) {
res.add(i - windowSize + 1);
}
}
return res;
}
}
Complexity
- Time = O(n)
- Space = O(n)
This post is licensed under CC BY 4.0 by the author.