Maximum Binary String After Change LeetCode solution in JavaScript

1
/**
2
* @param {string} binary
3
* @return {string}
4
*/
5
var maximumBinaryString = function (binary) {
6
/*
7
10 -> 01 allows us to move any zero to left by one position
8
00 -> 10 allows us to convert any consicutive 00 to 10
9
So we can collect all the zeros together then convert them in 1 except for the rightmost 0
10
We will club all the zeros togegher on the rightmost possition, to achieve the biggest value, then covert them into 1 except for the rightmost 0
11
So we need to choose indexOfFirstZero as the starting possition of the group of zeros
12
If there is no 0 then given string is the maximum possible string
13
If there are 1 or more zeros
14
Then there will be only 1 zero in the answer
15
Position of this will be indexOfFirstZero in given string + countOfZeros - 1
16
*/
17
let firstZeroIndex = -1,
18
zeroCount = 0,
19
ans = "";
20
for (let i = 0; i < binary.length; i++) {
21
if (binary[i] === "0") {
22
zeroCount++;
23
if (firstZeroIndex === -1) {
24
firstZeroIndex = i;
25
}
26
}
27
}
28
if (firstZeroIndex == -1) {
29
return binary;
30
}
31
let onlyZeroInAns = firstZeroIndex + (zeroCount - 1);
32
for (let i = 0; i < binary.length; i++) {
33
if (i == onlyZeroInAns) {
34
ans += "0";
35
} else {
36
ans += "1";
37
}
38
}
39
return ans;
40
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0