# Special Binary String in C++

C++Server Side ProgrammingProgramming

Suppose we have a spatial binary string. This string has following few properties −

• There are same number of 0s and 1s

• Every Prefix in the binary string has at least as many 1s as 0s

Now suppose we have special string S, a move is actually choosing two consecutive, non-empty, special substrings of S, and swapping them.

We have to find the lexicographically largest resulting string possible, at the end of any number of moves.

So, if the input is like 11011000, then the output will be 11100100, this is because: The substrings "10" and "1100" are swapped. This is the lexicographically largest string possible after few moves.

To solve this, we will follow these steps −

• Define a function makeLargestSpecial(), this will take s,

• ret := empty string

• Define an array v of strings

• i := 0

• for initialize j := 0, cnt := 0, when j < size of s, update (increase j by 1), do −

• if s[j] is same as '1', then −

• (increase cnt by 1)

• Otherwise

• (decrease cnt by 1)

• if cnt is same as 0, then −

• insert "1" + makeLargestSpecial(substring of s from index i + 1 to j - i - 1) at the end of v

• i := j + 1

• sort the array v.r

• for initialize i := 0, when i < size of v, update (increase i by 1), do −

• ret := ret + v[i]

• return ret

• From the main method call makeLargestSpecial() with the string.

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string makeLargestSpecial(string s) {
string ret = "";
vector<string> v;
int i = 0;
for (int j = 0, cnt = 0; j < s.size(); j++) {
if (s[j] == '1') {
cnt++;
}
else
cnt--;
if (cnt == 0) {
v.push_back("1" + makeLargestSpecial(s.substr(i + 1,
j - i - 1)) + "0");
i = j + 1;
}
}
sort(v.rbegin(), v.rend());
for (int i = 0; i < v.size(); i++)
ret += v[i];
return ret;
}
};
main(){
Solution ob;
cout << (ob.makeLargestSpecial("11011000"));
}

## Input

11011000

## Output

11100100
Updated on 08-Jun-2020 10:15:14