友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

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 即可。(交换一次,可以解决两个不正确比特位)。

  • 一刷

 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
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-09-24 16:26:07
 */
public int minSwaps(String s) {
  int[] bits = bits(s);
  int b0 = bits[0];
  int b1 = bits[1];
  int n = s.length();
  int result = Integer.MAX_VALUE;
  // 1010...
  if (b0 == n / 2 && b1 == (n + 1) / 2) {
    int diff = 0;
    for (int i = 0; i < n; i++) {
      if (s.charAt(i) - '0' == i % 2) {
        diff++;
      }
    }
    result = Math.min(result, diff / 2);
  }
  // 0101...
  if (b0 == (n + 1) / 2 && b1 == n / 2) {
    int diff = 0;
    for (int i = 0; i < n; i++) {
      if (s.charAt(i) - '0' != i % 2) {
        diff++;
      }
    }
    result = Math.min(result, diff / 2);
  }
  return result != Integer.MAX_VALUE ? result : -1;
}

private int[] bits(String s) {
  int b0 = 0;
  for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == '0') {
      b0++;
    }
  }
  return new int[]{b0, s.length() - b0};
}