알고리즘

2024 11 05 2914. Minimum Number of Changes to Make Binary String Beautiful

물빠진떡 2024. 11. 5. 20:46

문제

You are given a 0-indexed binary string s having an even length.

A string is beautiful if it's possible to partition it into one or more substrings such that:

Each substring has an even length.
Each substring contains only 1's or only 0's.
You can change any character in s to 0 or 1.

Return the minimum number of changes required to make the string s beautiful.

요약

0과 1로 이루어진 짝수 문자열에서 짝수길이의 동일한 문자만 가진 부분 문자로 나눌수 있게 최소한의 문자만 바꿔보아라

풀이

돌다가 이전 문자와 다른 문자가 나왔을때 이전문자열이 짝수인지 홀수인지 판단하고 바꾸면 됨

코드

class Solution {
    public int minChanges(String s) {
        char pre = s.charAt(0);
        boolean isEven = false;
        int result = 0;
        for (int i = 1; i < s.length(); i ++) {
            char c = s.charAt(i);
            if (pre == c) {
                isEven = !isEven;
                continue;
            }
            if (!isEven) {
                result ++;
            }
            if (isEven) {
                pre = c;
            }
            isEven = !isEven;
        }
        return result;
    }
}

풀이 시간

5분

체감 난이도

easy