Formatted question description: https://leetcode.ca/all/761.html

# 761. Special Binary String

Hard

## Description

Special binary strings are binary strings with the following two properties:

• The number of 0’s is equal to the number of 1’s.
• Every prefix of the binary string has at least as many 1’s as 0’s.

Given a special string S, a move consists of choosing two consecutive, non-empty, special substrings of S, and swapping them. (Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.)

At the end of any number of moves, what is the lexicographically largest resulting string possible?

Example 1:

Input: S = “11011000”

Output: “11100100”

Explanation:

The strings “10” [occuring at S[1]] and “1100” [at S[3]] are swapped. This is the lexicographically largest string possible after some number of swaps.

Note:

1. S has length at most 50.
2. S is guaranteed to be a special binary string as defined above.

## Solution

Use recursion. For each non-empty special substring, swap inside itself to form the lexicographically largest special substring, and then sort the special substrings to form the lexicographically largest special substring.

Obviously, each special substring must start with 1 and end with 0. Each time a smaller special substring is obtained, insert 1 at the start and insert 0 at the end to form a larger special substring.

• class Solution {
public String makeLargestSpecial(String S) {
List<String> list = new ArrayList<String>();
int start = 0;
int ones = 0;
int length = S.length();
for (int i = 0; i < length; i++) {
char c = S.charAt(i);
if (c == '1')
ones++;
else
ones--;
if (ones == 0) {
String substr = S.substring(start + 1, i);
String curSpecial = "1" + makeLargestSpecial(substr) + "0";
start = i + 1;
}
}
Collections.sort(list);
StringBuffer sb = new StringBuffer();
for (int i = list.size() - 1; i >= 0; i--)
sb.append(list.get(i));
return sb.toString();
}
}

• // OJ: https://leetcode.com/problems/special-binary-string/
// Time: O(N^2)
// Space: O(N)
// Ref: https://leetcode.com/problems/special-binary-string/solution/
class Solution {
public:
string makeLargestSpecial(string s) {
if (s.empty()) return "";
int N = s.size(), anchor = 0, cnt = 0;
vector<string> v;
for (int i = 0; i < N; ++i) {
cnt += s[i] == '1' ? 1 : -1;
if (cnt == 0) {
v.push_back("1" + makeLargestSpecial(s.substr(anchor + 1, i - anchor - 1)) + "0");
anchor = i + 1;
}
}
sort(begin(v), end(v), greater<>());
string ans;
for (auto &m : v) ans += m;
return ans;
}
};

• class Solution(object):
def makeLargestSpecial(self, S):
"""
:type S: str
:rtype: str
"""
cnt = 0
res = list()
i= 0
for j, v in enumerate(S):
cnt += 1 if v == "1" else -1
if cnt == 0:
res.append("1" + self.makeLargestSpecial(S[i + 1:j]) + "0")
i = j + 1
return "".join(sorted(res, reverse=True))