{leetcode}/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/[LeetCode - 1864. Minimum Number of Swaps to Make the Binary String Alternating ^]
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: "1[.underline]#1#10[.underline]#0#0" -> "1[.underline]#0#10[.underline]#1#0" 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'
.
如果是交替出现,那么只有 010…
或者 101…
这两种类型,统计各个比特位不正确的位数再除以 2 即可。(交换一次,可以解决两个不正确比特位)。
- 一刷
-
link:{sourcedir}/_1864_MinimumNumberOfSwapsToMakeTheBinaryStringAlternating.java[role=include]