DEV Community

hwangs12
hwangs12

Posted on

2022.05.15 Programming

Anagram

/**
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
var findAnagrams = function(s, p) {
    // let's create hashmap for p
    let champ = {}
    for (let pChar of p) {
        champ[pChar] ? champ[pChar]++ : champ[pChar] = 1
    }
    let right = 0
    let left = 0
    let count = p.length
    let output = new Array()

    while (right < s.length) {
        if (champ[s[right]] > 0) {
            count--
        }
        champ[s[right]]--
        right++

        if (count === 0) output.push(left)

        if (right - left === p.length) {
            if (champ[s[left]] >= 0) {
                count++

            }
            champ[s[left]]++
            left++
        }
    }
    return output
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)