文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
**解析:**Version 1,先找到第一个0
,然后找到其后的第一个1
,从这里开始,每碰到一个0
就将其置为1
,1
之后的数字对应的置为0
,相当于互换二者位置,这样让所有的0
集中在一起,然后执行第一条规则。Version 2,根据规则可知,第一个0
后面的零都应该跟其相连,即其后的数字顺序应按照0
和1
的顺序排序,然后将执行第一条规则。Version 3根据规则可知,如果字符串中的0
少于两个,则字符串没变化,0
多于1个时,最终结果只有1个0
,且其位置应该位于第一个0
之后的第count
位,count
为字符串中0
的总数。
- Version 1
class Solution:def maximumBinaryString(self, binary: str) -> str:digits = list(binary)n = len(digits)i = 0while i < n and digits[i] != '0':i += 1m = iwhile i < n and digits[i] != '1':i += 1k = ifor j in range(i, n):if digits[j] == '0':digits[j] = '1'digits[k] = '0'k += 1i = mwhile i < n - 1 and digits[i] == '0' and digits[i+1] == '0':digits[i] = '1'i += 1ans = ''.join(digits)return ans
- Version 2
class Solution:def maximumBinaryString(self, binary: str) -> str:digits = list(binary)n = len(digits)i = 0while i < n and digits[i] != '0':i += 1digits = digits[:i] + sorted(digits[i:])i = 0 while i < n - 1:if digits[i] == '0' and digits[i+1] == '0':digits[i] = '1'i += 1ans = ''.join(digits)return ans
- Version 3
class Solution:def maximumBinaryString(self, binary: str) -> str:digits = ['1'] * len(binary)count = binary.count('0')if count <= 1:return binaryn = len(digits)i = 0while i < n and binary[i] != '0':i += 1digits[i+count-1] = '0'ans = ''.join(digits)return ans
Reference
- https://leetcode.com/problems/maximum-binary-string-after-change/