Minimum Changes To Make Alternating Binary String LeetCode solution in Java

1
class Solution {
2
public int minOperations(String s) {
3
int count0 = 0; // changes required when the string starts from 0
4
int count1 = 0; // changes required when the string starts from 1
5

6
for (int i = 0; i < s.length(); i++) {
7

8
// string starts with 1 => all chars at even places should be 1 and that at odd places should
9
// be 0
10
if ((i % 2 == 0 && s.charAt(i) == '0') || (i % 2 != 0 && s.charAt(i) == '1')) count1++;
11

12
// string starts with 0 => all chars at even places should be 0 and that at odd places should
13
// be 1
14
else if ((i % 2 == 0 && s.charAt(i) == '1') || (i % 2 != 0 && s.charAt(i) == '0')) count0++;
15
}
16

17
// return minimum of the two
18
return Math.min(count0, count1);
19
}
20
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0