(Java)프로그래머스 - 문자열 나누기

윤준혁·2024년 3월 5일

나의 풀이

class Solution {
    public int solution(String s) {
        int answer = 1;
        char x = s.charAt(0); // 1
        int xcount = 1;
        int acount = 0;
        
        for (int i = 1; i < s.length() - 1; i++) {
            if (x == s.charAt(i)) { // 2
                xcount++;
            } else {
                acount++;
            }
            
            if (xcount == acount) { // 3
                answer++;
                x = s.charAt(i + 1);
            }
        }
        
        return answer;
    }
}

과정

  1. 시작 문자 x와 x의 카운트 1, 다른 카운트 acount 0을 선언(x는 이미 자신을 카운트하기때문에 1부터 시작)
  2. x가 s의 i번째 문자와 같으면 xcount를 1 더해주고, 다르면 acount를 1 더해준다
  3. xcount와 acount가 같아지면 answer에 1을 더해주고 x를 s의 i + 1번째 문자로 초기화해준다

다른 사람 풀이

public class Solution {
    public int solution(String s) {
        int answer = 0;
        char init = s.charAt(0);
        int count = 0;
        for (char c : s.toCharArray()) {
            if (count == 0) {
                init = c;
            }
            if (init == c) {
                count++;
            } else {
                count--;
            }
            if (count == 0) {
                answer++;
            }
        }

        if(count > 0) {
            answer++;
        }
        return answer;
    }
}

0개의 댓글