๊ด€๋ฆฌ ๋ฉ”๋‰ด

Daehyunii's Dev-blog

๋ชจ๋“  ์•„๋‚˜๊ทธ๋žจ ์ฐพ๊ธฐ(ํšจ์œจ์„ฑ-ํ•ด์‰ฌ,ํˆฌํฌ์ธํ„ฐ,์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ) ๋ณธ๋ฌธ

๐Ÿ“š Language & CS knowledge/Algorithm (๊ธฐ์ดˆ๋ฌธ์ œํ’€์ด)

๋ชจ๋“  ์•„๋‚˜๊ทธ๋žจ ์ฐพ๊ธฐ(ํšจ์œจ์„ฑ-ํ•ด์‰ฌ,ํˆฌํฌ์ธํ„ฐ,์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ)

Daehyunii 2022. 9. 2. 17:49

๋ฌธ์ œ(์ถœ์ฒ˜ : ์ธํ”„๋Ÿฐ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด ๊ฐ•์˜, ์ •๋ณด์˜ฌ๋ฆผํ”ผ์•„๋“œ)

 

S๋ฌธ์ž์—ด์—์„œ T๋ฌธ์ž์—ด๊ณผ ์•„๋‚˜๊ทธ๋žจ์ด ๋˜๋Š” S์˜ ๋ถ€๋ถ„๋ฌธ์ž์—ด์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜ ์„ธ์š”. ์•„๋‚˜๊ทธ๋žจ ํŒ๋ณ„์‹œ ๋Œ€์†Œ๋ฌธ์ž๊ฐ€ ๊ตฌ๋ถ„๋ฉ๋‹ˆ๋‹ค. ๋ถ€๋ถ„๋ฌธ์ž์—ด์€ ์—ฐ์†๋œ ๋ฌธ์ž์—ด์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

โ–ฃ ์ž…๋ ฅ์„ค๋ช…
์ฒซ ์ค„์— ์ฒซ ๋ฒˆ์งธ S๋ฌธ์ž์—ด์ด ์ž…๋ ฅ๋˜๊ณ , ๋‘ ๋ฒˆ์งธ ์ค„์— T๋ฌธ์ž์—ด์ด ์ž…๋ ฅ๋ฉ๋‹ˆ๋‹ค.
S๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋Š” 10,000์„ ๋„˜์ง€ ์•Š์œผ๋ฉฐ, T๋ฌธ์ž์—ด์€ S๋ฌธ์ž์—ด๋ณด๋‹ค ๊ธธ์ด๊ฐ€ ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์Šต๋‹ˆ๋‹ค.

โ–ฃ ์ถœ๋ ฅ์„ค๋ช…
S๋‹จ์–ด์— T๋ฌธ์ž์—ด๊ณผ ์•„๋‚˜๊ทธ๋žจ์ด ๋˜๋Š” ๋ถ€๋ถ„๋ฌธ์ž์—ด์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

 

โ–ฃ ์ž…๋ ฅ์˜ˆ์ œ 1

bacaAacba

abc

 

โ–ฃ ์ถœ๋ ฅ์˜ˆ์ œ 1

3

 

์ถœ๋ ฅ์„ค๋ช…: {bac}, {acb}, {cba} 3๊ฐœ์˜ ๋ถ€๋ถ„๋ฌธ์ž์—ด์ด "abc"๋ฌธ์ž์—ด๊ณผ ์•„๋‚˜๊ทธ๋žจ์ž…๋‹ˆ๋‹ค.

 

Tip

 

๋ฌธ์ œํ’€์ด

//๊ฐ•์˜ ์„ค๋ช…๋งŒ ๋“ฃ๊ณ  ๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ๋‹ต
function compare(h1,h2){
    if(h1.size !== h2.size) return false;
    for(let [key,val] of h1){
        // if(h1.get(key) !== h2.get(key)) return false;
        if(!h2.has(key)) return false;
        if(h2.get(key) !== val) return false;
    }
    return true;
}

function solution(str1, str2){
    let answer = 0;
    let sH = new Map();
    let tH = new Map();

    //tH
    for(let x of str2){
        if(tH.has(x))tH.set(x, tH.get(x)+1);
        else tH.set(x,1);
    }
    //sH
    for(let i = 0 ; i < str2.length-1 ; i++){
        if(sH.has(str1[i])) sH.set(str1[i], sH.get(str1[i])+1);
        else sH.set(str1[i],1);
    }



    //ํˆฌ ํฌ์ธํŠธ์™€ ๋™์‹œ์— ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ๋ฅผ ๋ฐ€๊ณ ๊ฐ€๋Š”๊ฒƒ์ด ๋‘˜ ๋‹ค ์ถ”์ƒ์  ๊ฐœ๋…์ด๋‹ค.
    let lt = 0;
    console.log('str1 >>>>', str1)
    for(let rt = str2.length - 1 ; rt < str1.length ; rt++){
        console.log('rt >>>', rt)
        if(sH.has(str1[rt])) {
            console.log('condition 1 >>>> ', true);
            sH.set(str1[rt], sH.get(str1[rt])+1);
        }
        else {
            console.log('case else')
            sH.set(str1[rt],1);
        }
        if(compare(sH,tH)) {
            console.log('condition 2 >>>> ', true);
            answer++;
        }

        sH.set(str1[lt],sH.get(str1[lt])-1);
        console.log('sH >>>', sH);

        if(sH.get(str1[lt]) === 0) {
            console.log('condition 3 >>> ', true);
            sH.delete(str1[lt]);
        }
        lt++;
    }
    return answer;
}

let a="bacaAacba";
let b="abc";
console.log(solution(a, b));