Commented Java Solution.


  • 2

    Any suggestion is greatly appreciated

    public class Solution {
        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> result = new ArrayList<Integer>();
            if(s.length() == 0 || p.length() == 0 || p.length() > s.length()) return result;
            boolean previous = false;
            int[] source = new int[26];
            int[] target = new int[26];
            /*Initilize the source and target counter*/
            for(char c : p.toCharArray()){
                target[(int) c - 'a']++;
            }
            for(char c : s.substring(0, p.length()).toCharArray()){
                source[(int) c - 'a']++;
            }
            /*check and add in the first substring if true*/
            if(isAnagrams(target, source)){
                result.add(0);
                previous = true;
            }
            /*sliding the window along the source*/
            for(int i = 1 ; i <= s.length() - p.length(); i++){
                /*if the previous substring is a anagram, only need to check
                  if the char comming into the window and the char leaving the window are the same*/
                if(previous && s.charAt(i-1) == s.charAt(i+p.length()- 1)){
                    result.add(i);
                }else{
                    source[(int)s.charAt(i-1) - 'a']--;
                    source[(int)s.charAt(i+p.length()-1) - 'a']++;
                    if(isAnagrams(source, target)){
                        result.add(i);
                        previous = true;
                    }else{
                        previous = false;
                    }
                }
            }
            return result;
        }
        
        /*helper function*/
        private boolean isAnagrams(int[] target, int[] source){
            for(int i = 0; i < target.length; i++){
                if(target[i] != source[i]) return false;
            }
            return true;
        }
    }````

Log in to reply
 

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