Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 973d494

Browse files
committed
Create 1888-minimum-number-of-flips-to-make-the-binary-string-alternating.java
1 parent e4396d1 commit 973d494

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public int minFlips(String s) {
3+
int n = s.length();
4+
s += s;
5+
6+
StringBuilder alt1 = new StringBuilder();
7+
StringBuilder alt2 = new StringBuilder();
8+
9+
for (int i = 0; i < s.length(); i++) {
10+
alt1.append(i % 2 == 0 ? '0' : '1');
11+
alt2.append(i % 2 == 0 ? '1' : '0');
12+
}
13+
14+
int res = Integer.MAX_VALUE;
15+
int diff1 = 0, diff2 = 0;
16+
int l = 0;
17+
for (int r = 0; r < s.length(); r++) {
18+
if (s.charAt(r) != alt1.charAt(r)) {
19+
diff1++;
20+
}
21+
if (s.charAt(r) != alt2.charAt(r)) {
22+
diff2++;
23+
}
24+
if ((r - l + 1) > n) {
25+
if (s.charAt(l) != alt1.charAt(l)) {
26+
diff1--;
27+
}
28+
if (s.charAt(l) != alt2.charAt(l)) {
29+
diff2--;
30+
}
31+
l++;
32+
}
33+
if ((r - l + 1) == n) {
34+
res = Math.min(res, Math.min(diff1, diff2));
35+
}
36+
}
37+
return res;
38+
}
39+
}

0 commit comments

Comments
 (0)