LeetCode 2914: Minimum Number of Changes to Make Binary String Beautiful
Problem Description
Explanation:
To solve this problem, we need to find the minimum number of changes required to make the input binary string beautiful. A beautiful string can be partitioned into substrings where each substring has an even length and contains only 0's or only 1's.
We can approach this problem by counting the number of changes needed to make all even-length substrings have the same character. We iterate through the string and check if the characters at even indices are the same, and if the characters at odd indices are the same. Then, we calculate the number of changes required by comparing the counts of 0's and 1's in even-length substrings.
:
Solutions
class Solution {
public int minOperations(String s) {
int count1 = 0, count2 = 0;
for (int i = 0; i < s.length(); i++) {
if (i % 2 == 0) {
if (s.charAt(i) != '0') {
count1++;
} else {
count2++;
}
} else {
if (s.charAt(i) != '1') {
count1++;
} else {
count2++;
}
}
}
return Math.min(count1, count2);
}
}
Loading editor...