dlehdanakf / Codingtest-Study

알고리즘 코딩테스트 토막지식 정리
1 stars 0 forks source link

SpecialStringAgain #11

Open dlehdanakf opened 3 years ago

dlehdanakf commented 3 years ago

Special String Again

풀이과정

function substrCount(n, s) {
    const arr = [];
    let str = [...s, '$'], [t] = str, c = 1;    // 문자열 끝에 $ 기호를 삽입, 맨 끝 문자까지 카운트를 용이하게 만든다.
    for(let i = 1; i < str.length; i++) {
        if(str[i] !== t) {
            arr.push({ t, c });
            t = str[i], c = 1;
        } else {
            c += 1;
        }
    }

    let answer = arr.reduce((acc, { c }) => acc + (c * (c+1)) / 2, 0);
    for(let i = 0; i < arr.length - 2; i++) {
        const { t: t0, c: c0 } = arr[i];
        const { t: t1, c: c1 } = arr[i+1];
        const { t: t2, c: c2 } = arr[i+2];
        if(t0 === t2 && c1 === 1) {
            answer += Math.min(c0, c2);
        }
    }

    return answer;
}