761 Special Binary String

# 1. Question

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`, amoveconsists 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:
1
Input: S = "11011000"
2
3
Output: "11100100"
4
5
Explanation:
6
The strings "10" [occuring at S] and "1100" [at S] are swapped.
7
This is the lexicographically largest string possible after some number of swaps.
Copied!
Note:
1. 1.
`S`has length at most`50`.
2. 2.
`S`is guaranteed to be a special binary string as defined above.

# 2. Implementation

(1) Recursion
1
class Solution {
2
public String makeLargestSpecial(String S) {
3
StringBuilder res = new StringBuilder();
4
List<String> vp = new ArrayList();
5
int count = 0, startIndex = 0;
6
7
for (int i = 0; i < S.length(); i++) {
8
count += S.charAt(i) == '1'? 1 : -1;
9
10
if (count == 0) {
11
vp.add("1" + makeLargestSpecial(S.substring(startIndex + 1, i)) + "0");
12
startIndex = i + 1;
13
}
14
}
15
16
Collections.sort(vp, Collections.reverseOrder());
17
18
for (String p : vp) {
19
res.append(p);
20
}
21
return res.toString();
22
}
23
}
Copied!

# 3. Time & Space Complexity

Recursion: 时间复杂度O(), 空间复杂度O()