프로그래머스 LEVEL 1(문자열 나누기)

image

  • 사용 언어 : javascript

  • 해결 날짜 : 2022-12-01

  • 해결 방법 :
    • 기준이 될 글자 (standard), 기준 글자의 갯수 (standardCount), 그 외 글자의 갯수 (otherCount) 초기화
    • 인자로 받은 문자열 s를 돌며
      • standard가 비어있는 경우 현재 글자를 standard로 설정, standardCount 증가
      • 현재 글자가 standard와 같은 경우 standardCount 증가
      • 그 외의 경우 현재 글자가 standard가 아니므로, standardCount와 otherCount를 1 증가한 값이 같은 경우
        • answer 증가
        • standardCount 초기화, otherCount 초기화, standard 초기화
    • 반복문 종료 후 standard가 비어 있는 문자열이면 모두 비교한 것이므로 answer 반환
    • 비어 있지 않다면 마지막 한 글자를 비교하지 못했으므로 answer + 1 반환
  • 회고 :
    • 처음에 기준이 될 글자와 그 외의 글자를 두 가지의 글자로만 생각했다.
    • 문제를 다시 읽어보니 standard 외의 모든 나머지 글자는 그 외의 글자가 되는 것 이었다.
    • 매번 느끼지만 쉬운 문제여도 문제를 똑바로 풀고 읽자
  • 코드

    function solution(s) {
        let answer = 0;
        let standard = '';
        let standardCount = 0;
        let otherCount = 0;
            
        for (const c of s) {
            if (standard === '') {
                standard = c;
                standardCount += 1;
            } else if (c === standard) {
                standardCount++;
            } else if (standardCount === ++otherCount) {
                answer++;
                standardCount = 0;
                otherCount = 0;
                standard = '';
            }
        }
            
        return standard.length === 0 ? answer : answer + 1;
    }
    
  • 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges