
java
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
int sLen = s.length();
int pLen = p.length();
//s字符串的长度小于p字符串,直接没有
if(sLen < pLen){
return result;
}
int[] pCount = new int[26];
int[] windowCount = new int[26];
//构建p的图谱和s的前pLen的图谱
for(int i = 0; i < pLen; i++){
pCount[p.charAt(i) - 'a']++;
windowCount[s.charAt(i) - 'a']++;
}
//先对前pLen个字符比较
if(Arrays.equals(pCount,windowCount)){
result.add(0);
}
//遍历pLen后面的字符
for(int right = pLen; right < sLen; right++){
int left = right - pLen;
windowCount[s.charAt(right) - 'a']++;
windowCount[s.charAt(left) - 'a']--;
if(Arrays.equals(pCount,windowCount)){
result.add(left + 1);
}
}
return result;
}
}
将初始化和循环分开写,减少if-else的使用