本题用滑动窗口和数组来解决,滑动窗口保存p字段的长度的s子串,比较所含元素是否相同,若相同则将索引放入一个ArrayList储存。
class Solution {
public List<Integer> findAnagrams(String s, String p) {
//int l = 0, r = p.length()-1;
int m = s.length(),n = p.length();
//两个数组储存s和p中字母出现次数
int[] sCnt = new int[26];
int[] pCnt = new int[26];
//res储存结果索引
List<Integer> res = new ArrayList<>();
if (m < n) {return new ArrayList<Integer>();}
//先将s,p字母出现次数初始化,然后判断0索引时是否相等
for (int i = 0; i < n; i ++) {
pCnt[p.charAt(i) - 'a']++;
sCnt[s.charAt(i) - 'a']++;
}
//若相等则向res中加入0索引
if (Arrays.equals(sCnt,pCnt)) {
res.add(0);
}
//将剩余字母遍历,每遍历一个字母,就删除最先放入的字母,再和pCnt比较是否相等
//若相等,说明相同,返回该位置索引
for(int i = n; i < m; i++){
sCnt[s.charAt(i - n) - 'a']--;
sCnt[s.charAt(i) - 'a']++;
if(Arrays.equals(sCnt, pCnt)){
res.add(i - n + 1);
}
}
return res;
}
}