滑动窗口算法的应用,通过两个while循环分别控制右指针和收缩条件
public List<Integer> findAnagrams(String s, String p) { List<Integer> res=new ArrayList<>(); Map<Character,Integer> need=new HashMap<>(); Map<Character,Integer> window=new HashMap<>(); int left=0,right=0,start=0; int index=0; int valid=0; char [] pCharArray=p.toCharArray(); for(char c:pCharArray) { need.put(c,need.getOrDefault(c,0)+1); } while(right<s.length()) { char r=s.charAt(right); right++; if(need.containsKey(r)) { window.put(r,window.getOrDefault(r,0)+1); if(window.get(r).equals(need.get(r))) valid++; } while(right-left>=p.length()) { if(valid==need.size()) res.add(left); char l=s.charAt(left); left++; if(need.containsKey(l)) { if(window.get(l).equals(need.get(l))) valid--; window.replace(l,window.get(l)-1); } } } return res; }