์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜5] ๋ชจ๋“  ์•„๋‚˜๊ทธ๋žจ ์ฐพ๊ธฐ (Javascript)

์€์ง„ 2021. 6. 25. 21:44

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜5] ๋ชจ๋“  ์•„๋‚˜๊ทธ๋žจ ์ฐพ๊ธฐ (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-25

1. ๋ถ€๋ถ„๋ฌธ์ž์—ด์„ ์ผ์ผ์ด str.substring()์œผ๋กœ ์ž˜๋ผ๋‚ด์•ผํ•˜๋‚˜? ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์€ ์—†๋‚˜?

2. ๋ฌธ์ž์—ด T๋ฅผ hash๋กœ ์ „ํ™˜

3. 2๋ฒˆ๊ณผ ๋™์‹œ์— ๋ฌธ์ž์—ด S๋ฅผ ๋ฌธ์ž์—ด T์˜ ๊ธธ์ด๋งŒํผ๋งŒ hash๋กœ ์ „ํ™˜

for (let i=0; i<len; i++) {
        hashS.set(strS[i], (hashS.get(strS[i]) || 0) + 1);
        hashT.set(strT[i], (hashT.get(strT[i]) || 0) + 1);
    }

์ฃผ์˜
์ดˆ๊ธฐ๊ฐ’ hashS๊ฐ€ hashT์™€ ์ผ์น˜ํ•˜๋Š”์ง€ ํ™•์ธํ•ด์•ผ ํ•จ

3. ๊ทธ ๋‹ค์Œ ๋ถ€๋ถ„๋ฌธ์ž์—ด ๊ตฌํ•˜๊ธฐ (hashS ์—…๋ฐ์ดํŠธ)

  • ๋ฐฉ๋ฒ• 1. left, right ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด hash.set(val, -1), hash.set(val, +1)
  • ๋ฐฉ๋ฒ• 2. ๋ณ€์ˆ˜ i ํ•˜๋‚˜๋งŒ ์‚ฌ์šฉํ•˜์—ฌ i๋ฒˆ์งธ ๋ฌธ์ž, i-len ์—ฐ์‚ฐ
hashS.set(strS[i], (hashS.get(strS[i]) || 0) + 1);
hashS.set(strS[i-len], hashS.get(strS[i]) - 1);

5. hashS์™€ hashT์˜ ์ผ์น˜์—ฌ๋ถ€ ํ™•์ธ

  • true/false์— ๋”ฐ๋ผ cnt++๋ฅผ ํ•˜๊ธฐ ์œ„ํ•ด, isEquel() ํ•จ์ˆ˜ ์ •์˜
function isEquel(hashS, hashT) {
    for (let [key, val] of hashT) {
        if (val !== hashS.get(key)) return false;
    }
    return true;
}

if (isEquel(hashS, hashT)) cnt++;


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-25

function isEquel(hashS, hashT) {
    for (let [key, val] of hashT) {
        if (val !== hashS.get(key)) return false;
    }
    return true;
}

function solution(strS, strT) {
    let cnt = 0;
    let hashS = new Map(), hashT = new Map();

    let len = strT.length;
    for (let i=0; i<len; i++) {
        hashS.set(strS[i], (hashS.get(strS[i]) || 0) + 1);
        hashT.set(strT[i], (hashT.get(strT[i]) || 0) + 1);
    }

    if (isEquel(hashS, hashT)) cnt++;

    for (let i=len; i<strS.length; i++) {
        hashS.set(strS[i], (hashS.get(strS[i]) || 0) + 1);
        hashS.set(strS[i-len], hashS.get(strS[i-len]) - 1);
        if(isEquel(hashS, hashT)) cnt++;
    }

    return cnt;
}