sliding window solution


  • 0
      public void getMap(String s, int []map){
            for(char x: s.toCharArray()){
                map[x-'a']++;
            }
        }
        public boolean check(String str, int []map){
            for(char x: str.toCharArray()){
                map[x-'a']--;
                if(map[x-'a'] < 0) return false;
            }
            return true;
        }
        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> res = new ArrayList<>();
            int len = p.length(), n = s.length();
            int [] map = new int[26];
            getMap(p, map);
            for(int i = 0; i < n; i++){
                if(i < n && i + len <= n){
                    String sub = s.substring(i, i+len);
                    int []map1 = map.clone();
                    if(check(sub, map1)){
                        res.add(i);
                    }
                }
            }
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.