Runtime beats 99.29% of java submissions


  • 0
    Q

    14ms solution. A bit verbose.

         public List<Integer> findAnagrams(String s, String p) {
            int SIZE = 'z' - 'a' + 1;
            byte[] count = new byte[SIZE];
            List<Integer> result = new ArrayList<Integer>();
            int i, j, lens = s.length(), lenp = p.length();
            for(i = 0; i < lens; ++i){
                if(i + lenp - 1 >= lens){
                    return result;
                }
                if(i == 0){
                    for(j = 0; j < lenp; j++){
                        count[p.charAt(j) - 'a']++;
                    }
                    for(j = i; j < i + lenp; j++){
                        count[s.charAt(j) - 'a']--;
                    }
                } else{
                    // remove the previous character
                    count[s.charAt(i - 1) - 'a']++;
                    // add the next character
                    count[s.charAt(i + lenp - 1) - 'a']--;
                }
                boolean matched = true;
                for(j = 0; j < SIZE; ++j){
                    if(count[j] != 0){
                        matched = false;
                        break;
                    }
                }
                if(matched){
                    result.add(i);
                }
           }
           return result;
        }
    

Log in to reply
 

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