Description
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".<ul> <li>For example, <code>"<u>00</u>010" -> "<u>10</u>010</code>"</li> </ul> </li> <li>Operation 2: If the number contains the substring <code>"10"</code>, you can replace it with <code>"01"</code>. <ul> <li>For example, <code>"000<u>10</u>" -> "000<u>01</u>"</code></li> </ul> </li>
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
- binaryconsist of- '0'and- '1'.
Solution
Python3
class Solution:
    def maximumBinaryString(self, binary: str) -> str:
        if "0" not in binary: return binary
        
        idx = binary.index("0")
        
        res = []
        for _ in range(idx):
            res.append("1")
        
        ones = zeroes = 0
        for i in range(idx, len(binary)):
            if binary[i] == "1": ones += 1
            else: zeroes += 1
        
        while zeroes > 1:
            res.append("1")
            zeroes -= 1
        
        res.append("0")
        
        while ones > 0:
            res.append("1")
            ones -= 1
        
        return "".join(res)