-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy path761.special-binary-string.cpp
More file actions
63 lines (56 loc) · 1.79 KB
/
761.special-binary-string.cpp
File metadata and controls
63 lines (56 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Tag: String, Divide and Conquer, Sorting
// Time: -
// Space: -
// Ref: -
// Note: -
// 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.
//
// 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 <= 50
// s[i] is either '0' or '1'.
// s is a special binary string.
//
//
class Solution {
public:
string makeLargestSpecial(string s) {
int count = 0;
int i = 0;
vector<string> res;
for (int j = 0; j < s.size(); j++) {
count = s[j] == '1' ? count + 1 : count - 1;
if (count == 0) {
string inner = makeLargestSpecial(s.substr(i + 1, j - i - 1));
res.push_back("1" + inner + "0");
i = j + 1;
}
}
sort(res.begin(), res.end(), greater<string>());
string ans;
for (auto &str : res) {
ans += str;
}
return ans;
}
};