문제
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
'알고리즘' 카테고리의 다른 글
2024 11 09 3133. Minimum Array End (0) | 2024.11.09 |
---|---|
2024 11 06 3011. Find if Array Can Be Sorted (0) | 2024.11.06 |
2024 11 04 3163. String Compression III (1) | 2024.11.04 |
2024 11 03 Result796. Rotate String (1) | 2024.11.03 |
2024 11 02 2490. Circular Sentence (0) | 2024.11.02 |