class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res=new ArrayList<>();
int l=0;
int r=0;
int match=0;
Map<Character,Integer> window=new HashMap<>();
Map<Character,Integer> needs=new HashMap<>();
for(int i=0;i<p.length();i++){
char ch=p.charAt(i);
needs.put(ch,needs.getOrDefault(ch,0)+1);
}
while(r<s.length()){
char ch=s.charAt(r);
if(needs.containsKey(ch)){
window.put(ch,window.getOrDefault(ch,0)+1);
//一定要记得加intValue()
if(window.get(ch).intValue()==needs.get(ch).intValue()){//如果该词出现的个数等于需要的个数
match++;
}
}
r++;
while(match==needs.size()){ //如果所有需要的字符都满足了
if((r-l)==p.length()){ //窗口长度一定要等于p长度才叫字母异位词
res.add(l);
}
char ch2=s.charAt(l);
if(needs.containsKey(ch2)){
window.put(ch2,window.getOrDefault(ch2,0)-1); //window里ch2字符的数量减一
//一定要转化成intValue()
if(window.get(ch2).intValue()<needs.get(ch2).intValue()){ //如果ch2字符不满足需求则match--;
match--;
}
}
l++;
}
}
return res;
}
}
leetcode 438找到字符串中所有字母异位词
最新推荐文章于 2023-07-10 22:27:49 发布