Java 15ms solution , easy to understand


  • 0
    public List<Integer> findAnagrams(String s, String p) {
            List<Integer> record = new ArrayList<>();
            if(s==null || s.length()==0 || s.length()<p.length())  
                return record;
            
            int len1 = s.length(), len2 = p.length();
            int[] t = new int[26];
            
            //compare the first window with p. if they are the anagrams, all elements in the array t will be 0
            int i = 0;         
            for(int j=i ; j<len2; j++){
                t[s.charAt(j)-'a'] ++;
                t[p.charAt(j)-'a'] --;
            }
    
            //if all elements in t are 0, add the current index to record;
            int k = 0;
            for(; k<26; k++){
                if(t[k] != 0)
                    break;
            }
            if(k == 26)     
                record.add(i);
                
            for(i=1; i<=len1-len2; i++){
               //each time the window slides,we just need to think about the change between beginning and end of the window
                t[s.charAt(i-1)-'a']--;      
                t[s.charAt(i+len2-1)-'a']++;
                
                k = 0;
                for(; k<26; k++){
                    if(t[k] != 0)
                        break;
                }
                if(k == 26)
                    record.add(i);
            }
            
            return record;
            
        }
    

Log in to reply
 

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