欢迎访问原文所在博客:https://52heartz.top/articles/leetcode-438-find-all-anagrams-in-a-string/
解法1[Java]:
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<>();
if (s == null || p == null || p.length() > s.length()) {
return res;
}
int[] map = new int[128];
for (char ch : p.toCharArray()) {
map[ch]++;
}
int left = 0, right = 0;
int len_s = s.length();
int len_p = p.length();
while (right < len_s) {
char ch_r = s.charAt(right);
map[ch_r]--;
while (map[ch_r] < 0) {
char ch_l = s.charAt(left++);
map[ch_l]++;
}
if (right - left + 1 == len_p) {
res.add(left);
}
right++;
}
return res;
}
}
思路
先设计了一个 map,把 p 中所有的字符在 map 中的值先加1。
然后设计两个指针,右指针指向哪个字符,就把这个字符在 map 中对应的值减去 1。如果指向的字符不在 p 中,会导致那个字符对应的值小于0,根据这个条件,把左指针一步一步移到和右指针相同的位置,并且在移动的过程中把 map 恢复成最初的数值。这样就相当于从一个新的位置重新开始。