Given a binary string s
, return the minimum number of character swaps to make it alternating, or -1
if it is impossible.
The string is called alternating if no two adjacent characters are equal. For example, the strings "010"
and "1010"
are alternating, while the string "0100"
is not.
Any two characters may be swapped, even if they are not adjacent.
Example 1:
Input: s = "111000" Output: 1 Explanation: Swap positions 1 and 4: "111000" -> "101010" The string is now alternating.
Example 2:
Input: s = "010" Output: 0 Explanation: The string is already alternating, no swaps are needed.
Example 3:
Input: s = "1110" Output: -1
Constraints:
1 <= s.length <= 1000
s[i]
is either'0'
or'1'
.
Companies:
Société Générale
Related Topics:
Greedy
Count number of 0
s and 1
s. If either count is greater than 1
+ the other count, return -1
. Otherwise, we can try putting 0
or 1
at the first position and use two pointers to try to swap the numbers.
// OJ: https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
int solve(string s, int first) {
int i = 0, j = 1, N = s.size(), ans = 0;
while (i < N && j < N) {
while (i < N && s[i] == '0' + first) i += 2;
while (j < N && s[j] == '0' + 1 - first) j += 2;
if (i < N && j < N) {
swap(s[i], s[j]);
++ans;
}
}
return ans;
}
public:
int minSwaps(string s) {
int one = 0, zero = 0;
for (char c : s) {
if (c == '1') one++;
else zero++;
}
if (zero > one + 1 || one > zero + 1) return -1;
int ans = INT_MAX;
if (zero >= one) ans = min(ans, solve(s, 0));
if (zero <= one) ans = min(ans, solve(s, 1));
return ans;
}
};