๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 438 - Find All Anagrams in a String (Medium)

by HandHand 2023. 5. 14.

 

๐Ÿ’ก ๋ฌธ์ œ

LeetCode - 438๋ฒˆ

 

๐ŸŽฏ ํ’€์ด ๊ณผ์ •

๋ฌธ์ž์—ด s ์—์„œ p ์˜ ์•„๋‚˜๊ทธ๋žจ์„ ๋งŒ์กฑํ•˜๋Š” ๋ชจ๋“  ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์˜ ์œ„์น˜๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ๊ณ ๋ คํ•ด์„œ ์ตœ์ ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•ด์•ผํ•˜๋Š”๋ฐ, sliding window ๋ฅผ ํ™œ์šฉํ•˜๋ฉด

O(n) ์— ๋ชจ๋“  ์œ„์น˜์—์„œ ์•„๋‚˜๊ทธ๋žจ์„ ํŒ๋‹จํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๋จผ์ € p ๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ๋ฌธ์ž ๋นˆ๋„์ˆ˜ ํ•ด์‹œ๋งต์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

์ดํ›„ ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ left ์™€ right , ์•„๋‚˜๊ทธ๋žจ ๊ตฌ์„ฑ์— ํ•„์š”ํ•œ ๋ฌธ์ž ๊ฐœ์ˆ˜์˜ ํ•ฉ์„ ์œ„ํ•œ count ๋ฅผ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.

count ๊ฐ€ 0์ด ๋˜๋ฉด ๋ชจ๋“  ๋ฌธ์ž๋“ค์ด ํ•„์š”ํ•œ ๋นˆ๋„์ˆ˜๋งŒํผ ๋ฐœ๊ฒฌ๋˜์—ˆ๋‹ค๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

window ์˜ ํฌ๊ธฐ๋Š” ๊ณง p ์˜ ๊ธธ์ด์™€ ๊ฐ™๊ธฐ ๋•Œ๋ฌธ์— left ์™€ right ๊ฐ„์˜ ๊ฐ„๊ฒฉ์ด window size ์— ๋„๋‹ฌํ•˜๋ฉด

left ๋ฅผ ํ•˜๋‚˜ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์˜ฎ๊ฒจ์ฃผ๋Š” ๊ณผ์ •์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.

์ด๋•Œ ์ด ๋ฌธ์ž๊ฐ€ ์•„๋‚˜๊ทธ๋žจ ๊ตฌ์„ฑ์— ํ•„์š”ํ–ˆ๋˜ ๋ฌธ์ž๋ผ๋ฉด count ๋ฅผ ํ•˜๋‚˜ ์ฆ๊ฐ€์‹œ์ผœ์ค๋‹ˆ๋‹ค.

๐Ÿ‘จ‍๐Ÿ’ป ์ฝ”๋“œ

/**
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
var findAnagrams = function(s, p) {
    const needed = freq(p)
    const windowSize = p.length

    if (windowSize > s.length) {
        return []
    }

    let left = 0
    let right = 0
    let count = p.length
    const answer = []

    while (right < s.length) {
        if (needed[s[right]] > 0) {
            count -= 1
        }
        needed[s[right]] -= 1

        if (count === 0) {
            answer.push(left)
        }

        const isMaxWindowSize = (right - left + 1) === windowSize
        if (isMaxWindowSize) {
            if (needed[s[left]] >= 0) {
                count += 1
            }
            needed[s[left]] += 1
            left += 1
        }

        right += 1
    }

    return answer
};

function freq(str) {
    const result = {}

    for (let idx = 0; idx < str.length; idx += 1) {
        const char = str[idx]
        if (char in result) {
            result[char] += 1
        } else {
            result[char] = 1
        }
    }

    return result
}

 

๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 328 - Odd Even Linked List (Medium)  (0) 2023.05.29
LeetCode 704 - Binary Search (Easy)  (0) 2023.05.14
LeetCode 42 - Trapping Rain Water (Hard)  (0) 2023.04.30
LeetCode 238 - Product of Array Except Self (Medium)  (2) 2023.04.24
LeetCode 2390 - Removing Stars From a String (Medium)  (0) 2023.04.24

๐Ÿ’ฌ ๋Œ“๊ธ€