개발_자 2024. 8. 29. 09:40

function solution(s) {
    let stack = [];
    let count = 0;
    for(let i = 0; i < s.length; i++) {
        stack.push(s[i]);
        const same = stack.filter((item) => item === stack[0]);
        const notSame = stack.filter((item) => item !== stack[0]);
        if(same.length === notSame.length) {
            count++;
            stack = [];
        }
    }
    if(stack.length !== 0) {
        count += 1;
    }
    return count;
}

`apple`로 예를 들면

for문을 통해 apple을 순회합니다.

 

`a`를 stack에 추가하고

stack배열의 첫 번째 단어와 같은지 검사합니다.

같기 때문에 same에 할당합니다.

 

`p`를 stack에 추가하고 stack = [`a`, `p`];

stack배열의 첫 번째 단어와 같은지 검사합니다. `p` ≠ `a`

다르기 때문에 notsame에 할당, same과 notsame의 길이가 같으므로 카운트 업해주고 count = 1;

stack을 초기화 시킵니다.

 

 

p (same: 1, notSame: 0) → 계속 진행

pl (same: 1, notSame: 1) → count = 2, stack 초기화

e (same: 1, notSame: 0) → 계속 진행, for문 끝

남은 문자 있음 (e) → count 증가, count = 3