Description
Special binary strings are binary strings with the following two properties:
- The number of
0's is equal to the number of1's. - Every prefix of the binary string has at least as many
1's as0's.
You are given a special binary 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.
Return the lexicographically largest resulting string possible after applying the mentioned operations on the string.
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.
Example 2:
Input: s = "10" Output: "10"
Constraints:
1 <= s.length <= 50s[i]is either'0'or'1'.sis a special binary string.
Solutions
This function recursively rearranges a string of 1s and 0s to create the lexicographically largest special string, where a special string has equal 1s and 0s with all prefixes having at least as many 1s as 0s. The algorithm uses a counter that increments for each 1 and decrements for each 0; whenever the counter reaches zero, it has found a balanced "special" section delimited by matching 1 at the start and 0 at the end. For each balanced section, it recursively processes the inner content (the substring between the outer 1 and 0) and wraps it back with "1" + special + "0". Finally, it sorts all processed sections in reverse order and joins them together, ensuring the lexicographically largest result appears first.
/**
* @param {string} s
* @return {string}
*/
var makeLargestSpecial = function (s) {
let count = 0;
let i = 0;
let res = [];
for (let j = 0; j < s.length; j++) {
if (s[j] === '1') {
count++;
} else {
count--;
}
if (count === 0) {
const current = s.substring(i + 1, j);
const special = makeLargestSpecial(current);
res.push("1" + special + "0");
i = j + 1;
}
}
res.sort().reverse();
return res.join("");
};