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.
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.
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.
To get the lexicographically largest string, we need to place larger special substrings before smaller ones. A special binary string can be decomposed into consecutive special substrings, and we can recursively optimize each part.
#include<string>#include<vector>#include<algorithm>usingnamespace std;
string makeLargestSpecial(string s) {
if (s.length() <=2) return s;
vector<string> substrings;
int count =0, start =0;
for (int i =0; i < s.length(); i++) {
count += (s[i] =='1') ?1:-1;
if (count ==0) {
// Found a complete special substring from start to i
string inner = s.substr(start +1, i - start -1);
substrings.push_back("1"+ makeLargestSpecial(inner) +"0");
start = i +1;
}
}
// Sort in descending order for lexicographically largest result
sort(substrings.begin(), substrings.end(), greater<string>());
string result ="";
for (const string& sub : substrings) {
result += sub;
}
return result;
}
classSolution {
funmakeLargestSpecial(s: String): String {
if (s.length <=2) return s
val substrings = mutableListOf<String>()
var count = 0var start = 0for (i in s.indices) {
count +=if (s[i] =='1') 1else -1if (count ==0) {
val inner = s.substring(start + 1, i)
substrings.add("1" + makeLargestSpecial(inner) + "0")
start = i + 1 }
}
substrings.sortDescending()
return substrings.joinToString("")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
defmakeLargestSpecial(s: str) -> str:
if len(s) <=2:
return s
substrings = []
count =0 start =0for i, char in enumerate(s):
count +=1if char =='1'else-1if count ==0:
inner = s[start +1:i]
substrings.append("1"+ makeLargestSpecial(inner) +"0")
start = i +1# Sort in descending order for lexicographically largest result substrings.sort(reverse=True)
return''.join(substrings)
functionmakeLargestSpecial(s: string):string {
if (s.length<=2) returns;
constsubstrings: string[] = [];
letcount=0;
letstart=0;
for (leti=0; i<s.length; i++) {
count+=s[i] ==='1'?1:-1;
if (count===0) {
constinner=s.substring(start+1, i);
substrings.push("1"+makeLargestSpecial(inner) +"0");
start=i+1;
}
}
// Sort in descending order for lexicographically largest result
substrings.sort((a, b) =>b.localeCompare(a));
returnsubstrings.join("");
}