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,
"00010" -> "10010
“
- For example,
- Operation 2: If the number contains the substring
"10"
, you can replace it with"01"
.- For example,
"00010" -> "00001"
- For example,
Return the maximum 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.
Example 1:
Input: binary = "000110" Output: "111011" Explanation: A valid transformation sequence can be: "000110" -> "000101" "000101" -> "100101" "100101" -> "110101" "110101" -> "110011" "110011" -> "111011"
Example 2:
Input: binary = "01" Output: "01" Explanation: "01" cannot be transformed any further.
Constraints:
1 <= binary.length <= 105
binary
consist of'0'
and'1'
.
Solution: Greedy + Counting
Leading 1s are good, no need to change them.
For the rest of the string
1. Apply operation 2 to make the string into 3 parts, leading 1s, middle 0s and tailing 1s.
e.g. 11010101 => 11001101 => 11001011 => 11000111
2. Apply operation 1 to make flip zeros to ones except the last one.
e.g. 11000111 => 11100111 => 11110111
There will be only one zero (if the input string is not all 1s) is the final largest string, the position of the zero is leading 1s + zeros – 1.
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Solution { public: string maximumBinaryString(string s) { const int n = s.length(); int l = 0; int z = 0; for (char& c : s) { if (c == '0') { ++z; } else if (z == 0) { // leading 1s ++l; } c = '1'; } if (l != n) s[l + z - 1] = '0'; return s; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment