[LeetCode] Special Binary String

761. Special Binary String

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
unordered_map<string, string> dp;
public:
string makeLargestSpecial(string s) {
if(dp.count(s)) return dp[s];
int n = s.length();
vector<string> A;
for(int l = 0, r = 0, count = 0; r < n; r++) {
if(s[r] == '1') count++;
else count--;

if(count == 0) {
A.push_back('1' + makeLargestSpecial(s.substr(l + 1, r - l - 1)) + '0');
l = r + 1;
}
}
sort(rbegin(A), rend(A));
string res = "";
for(int i = 0; i < A.size(); i++) {
res += A[i];
}
return dp[s] = res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/04/PS/LeetCode/special-binary-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.