Skip to content

Commit d9f208b

Browse files
committed
Create: 1888-minimum-number-of-flips-to-make-the-binary-string-alternating.ts
1 parent 788a95f commit d9f208b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
function minFlips(s: string): number {
2+
if (!s || s.length < 1) return 0;
3+
4+
const initialLen = s.length;
5+
if (initialLen % 2 === 1) s += s;
6+
7+
let evenCmp = 0;
8+
let oddCmp = 0;
9+
let result = Infinity;
10+
let end = 0;
11+
let start = 0;
12+
13+
while (end < s.length) {
14+
if (end % 2 !== Number(s[end])) evenCmp++;
15+
if ((end % 2 ^ 1) !== Number(s[end])) oddCmp++;
16+
17+
if (end >= initialLen) {
18+
if (start % 2 !== Number(s[start])) evenCmp--;
19+
if ((start % 2 ^ 1) !== Number(s[start])) oddCmp--;
20+
start++;
21+
}
22+
23+
if (end >= initialLen - 1) {
24+
result = Math.min(evenCmp, oddCmp, result);
25+
}
26+
end++;
27+
}
28+
29+
return result;
30+
}

0 commit comments

Comments
 (0)