1. 程式人生 > 其它 >leetcode 找到字串中所有字母的異位詞

leetcode 找到字串中所有字母的異位詞

滑動視窗演算法的應用,通過兩個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; }