[LeetCode] Maximum Binary String After Change

1702. Maximum Binary String After Change

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”
  • Operation 2: If the number contains the substring “10”, you can replace it with “01”.
  • For example, “00010” -> “00001”

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.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
string maximumBinaryString(string s) {
int zero = count(begin(s), end(s), '0'), one = count(begin(s), end(s), '1');
for(int i = 0; i < s.length(); i++) {
if(s[i] == '1') one--;
else return string(i,'1') + string(zero - 1, '1') + "0" + string(one, '1');
}
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/16/PS/LeetCode/maximum-binary-string-after-change/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.