Skip to content

Commit e0da1f4

Browse files
authored
Create minimum-number-of-swaps-to-make-the-binary-string-alternating.cpp
1 parent 6e5eeaa commit e0da1f4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int minSwaps(string s) {
7+
int ones = count(cbegin(s), cend(s), '1');
8+
int zeros = size(s) - ones;
9+
if (abs(ones - zeros) > 1) {
10+
return -1;
11+
}
12+
if (ones > zeros) {
13+
return cost(s, 1);
14+
}
15+
if (ones < zeros) {
16+
return cost(s, 0);
17+
}
18+
return min(cost(s, 1), cost(s, 0));
19+
}
20+
21+
private:
22+
int cost(const string& s, int x) {
23+
int diff = 0;
24+
for (const auto& c : s) {
25+
diff += (c - '0' != x);
26+
x ^= 1;
27+
}
28+
return diff / 2;
29+
}
30+
};

0 commit comments

Comments
 (0)