Accepted Javascript solution


  • 0
    W

    Using the well-known template

    /**
     * @param {string} s
     * @param {string} p
     * @return {number[]}
     */
    var findAnagrams = function(s, p) {
        let res = [];
        if(p.length > s.length){
            return res;
        }
        
        let map = new Map();
       
        for(let c of p){
            map.set(c, (map.get(c) | 0) + 1);
        }
        
        let begin= 0, end= 0, counter= map.size;
     
        
        while(end < s.length){
            let c = s.charAt(end);
            
            if(map.has(c)){
                map.set(c, map.get(c) - 1);
                if (map.get(c) === 0) {
                    counter--;
                }
            }
            end++;
            while(counter===0){
                let d = s.charAt(begin);
                if(map.has(d)){
                   map.set(d, map.get(d) + 1); 
                   if(map.get(d) > 0 ){
                       counter++;
                   }
                }
                if(end - begin == p.length){
                    res.push(begin);
                }
                begin++;
            }
            
        }
        
        return res;
        
    };
    

Log in to reply
 

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