본문 바로가기
Beakjoon&프로그래머스/Java

[프로그래머스/Java] 문자열 나누기

by 현장 2025. 2. 27.

-Code

class Solution {
    public int solution(String s) {
        int answer = 0;
        int same = 0, different = 0;
        String now = "";

        for (String el : s.split("")) {
            if (now.isEmpty()) {
                now = el;
            }
            if (now.equals(el)) same++;
            else different++;
            
            if (same == different) {
                answer++;
                now = "";
                same = different = 0;
            }
        }

        return answer + (now.isEmpty() ? 0 : 1);
    }
}