Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

나 개발자 할래요

[JS] 문자열 나누기 본문

개발자 되는 법.../코딩테스트...

[JS] 문자열 나누기

개발_자 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

 

'개발자 되는 법... > 코딩테스트...' 카테고리의 다른 글

외계어 사전  (0) 2025.01.24
숨어있는 숫자의 덧셈 (2)  (0) 2025.01.24
[JS] 체육복  (0) 2024.08.27
[JS] 옹알이  (0) 2024.08.21
[JS] 로또의 최고 순위와 최저 순위  (0) 2024.08.20