You are given a binary string binary consisting of only 0’s or 1’s. You can apply each of the following operations any number of times:
Operation 1: If the number contains the substring "00", you can replace it with "10".
For example, "_00_ 010" -> "_10_ 010"
Operation 2: If the number contains the substring "10", you can replace it with "01".
For example, "000 _10_ " -> "000 _01_ "
Return themaximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x’s decimal representation is greater than y’s decimal representation.
The operations allow us to move all zeros to the right and then convert all but one zero to ones. The only zero left will be at the leftmost possible position after the first one. This is because every “00” can be turned into “10” and every “10” into “01”, so all zeros can be pushed together and then converted except one.
classSolution {
public String maximumBinaryString(String binary) {
int n = binary.length(), zeros = 0, first =-1;
for (int i = 0; i < n; ++i) {
if (binary.charAt(i) =='0') {
zeros++;
if (first ==-1) first = i;
}
}
if (zeros <= 1) return binary;
char[] ans =newchar[n];
Arrays.fill(ans, '1');
ans[first + zeros - 1]='0';
returnnew String(ans);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funmaximumBinaryString(binary: String): String {
val n = binary.length
var zeros = 0var first = -1for (i in binary.indices) {
if (binary[i] =='0') {
zeros++if (first == -1) first = i
}
}
if (zeros <=1) return binary
val ans = CharArray(n) { '1' }
ans[first + zeros - 1] = '0'return String(ans)
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defmaximumBinaryString(self, binary: str) -> str:
n = len(binary)
zeros = binary.count('0')
if zeros <=1:
return binary
first = binary.find('0')
ans = ['1'] * n
ans[first + zeros -1] ='0'return''.join(ans)