https://leetcode.com/problems/find-all-anagrams-in-a-string/
这一题,其实和很多题目都一样或者类似,先通过字符串p算出一个字符table, 然后就是维持一个window,数一下window里面各个字符有多少,然后匹配到p字符串的字符table,如果相同就记录。代码如下:
public List<Integer> findAnagrams(String s, String p) {
int[] curCounts = new int[26];
int[] pCounts = new int[26];
for (char c : p.toCharArray()) {
pCounts[c - 'a']++;
}
List<Integer> res = new LinkedList<>();
int curCount = 0;
for (int i = 0; i < s.length(); i++) {
if (i >= p.length()) {
int oldIndex = s.charAt(i - p.length()) - 'a';
curCounts[oldIndex]--;
if (pCounts[oldIndex] > 0 && curCounts[oldIndex] < pCounts[oldIndex]) {
curCount--;
}
}
int newIndex = s.charAt(i) - 'a';
curCounts[newIndex]++;
if (pCounts[newIndex] > 0 && curCounts[newIndex] <= pCounts[newIndex]) {
curCount++;
}
if (curCount == p.length()) {
res.add(i - p.length() + 1);
}
}
return res;
}