-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathSpecial Binary String.cpp
More file actions
79 lines (58 loc) · 2.08 KB
/
Special Binary String.cpp
File metadata and controls
79 lines (58 loc) · 2.08 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* Scroll below to see JAVA code also */
/*
MY YOUTUBE VIDEO ON THIS Qn : https://www.youtube.com/watch?v=EJ4hBpyYGDM
Company Tags : Coursera, Quip
Leetcode Link : https://leetcode.com/problems/special-binary-string
*/
/************************************************************ C++ ******************************************************/
//Approach : (Recursion)
//T.C : ~O(n^2)
//S.C : O(n) stack space and to store special substrings
class Solution {
public:
string makeLargestSpecial(string s) {
vector<string> specials;
int start = 0;
int sum = 0;
for(int i = 0; i < s.length(); i++) {
sum += s[i] == '1' ? 1 : -1;
if(sum == 0) {
string inner = s.substr(start+1, i-start-1);
specials.push_back("1" + makeLargestSpecial(inner) + "0");
start = i+1;
}
}
sort(begin(specials), end(specials), greater<string>());
string result;
for(string &str : specials) {
result += str;
}
return result;
}
};
/************************************************************ JAVA ******************************************************/
//Approach : (Recursion)
//T.C : ~O(n^2)
//S.C : O(n) stack space and to store special substrings
class Solution {
public String makeLargestSpecial(String s) {
List<String> specials = new ArrayList<>();
int count = 0;
int start = 0;
for (int i = 0; i < s.length(); i++) {
count += (s.charAt(i) == '1') ? 1 : -1;
if (count == 0) {
String inner = s.substring(start + 1, i);
String processed = "1" + makeLargestSpecial(inner) + "0";
specials.add(processed);
start = i + 1;
}
}
Collections.sort(specials, Collections.reverseOrder());
StringBuilder result = new StringBuilder();
for (String str : specials) {
result.append(str);
}
return result.toString();
}
}