📌  相关文章
📜  使二进制字符串交替所需的最小相邻交换

📅  最后修改于: 2022-05-13 01:56:09.139000             🧑  作者: Mango

使二进制字符串交替所需的最小相邻交换

给定一个大小为N的二进制字符串S ,任务是找到使字符串交替所需的最小相邻交换次数。如果无法这样做,则打印-1

例子:

方法:为了使字符串交替在第一个位置获得“1”“0” 。当字符串长度为偶数时,字符串必须以“0”“1”开头。当字符串的长度为奇数时,有两种可能的情况——如果不是。字符串中1 的个数大于字符串中0 的字符串,字符串必须以“ 1”开头。否则,如果没有。 of 0's大于 no of 1's ,字符串必须以“0”开头。因此,请检查二进制字符串在第一个位置以“1”开头和在第一个位置以“0”开头的两种情况。请按照以下步骤解决问题:

  • 将变量onezeros初始化为0以计算字符串中的 zeros 和 one 的数量。
  • 使用变量i遍历范围[0, N)并计算二进制字符串中01 的数量。
  • 检查基本情况,即如果N是偶数,那么如果等于1 。如果N是奇数,那么它们之间的差应该是1。如果基本情况不满足,则返回-1
  • 将变量ans_1初始化为0以存储字符串以1开头且j0 时的答案。
  • 使用变量i在范围[0, N)上迭代,如果s[i]等于1 ,则将abs(ji)的值添加到变量ans_1并将j的值增加2
  • 同样,将变量ans_0初始化为0以在字符串以1开头且k0时存储答案。
  • 使用变量i在范围[0, N)上迭代,如果s[i]等于0 ,则将abs(k – i)的值添加到变量ans_0并将k的值增加2
  • 如果N是偶数,则打印ans_1ans_0的最小值作为结果。否则,如果zeros大于one ,则打印 ans_0 否则,打印ans_1

下面是 上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the minimum number
// of adjacent swaps to make the string
// alternating
int minSwaps(string s)
{
    // Count the no of zeros and ones
    int ones = 0, zeros = 0;
    int N = s.length();
 
    for (int i = 0; i < N; i++) {
        if (s[i] == '1')
            ones++;
        else
            zeros++;
    }
 
    // Base Case
    if ((N % 2 == 0 && ones != zeros)
        || (N % 2 == 1
            && abs(ones - zeros) != 1)) {
        return -1;
    }
 
    // Store no of min swaps when
    // string starts with "1"
    int ans_1 = 0;
 
    // Keep track of the odd positions
    int j = 0;
 
    // Checking for when the string
    // starts with "1"
    for (int i = 0; i < N; i++) {
        if (s[i] == '1') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_1 += abs(j - i);
            j += 2;
        }
    }
 
    // Store no of min swaps when string
    // starts with "0"
    int ans_0 = 0;
 
    // Keep track of the odd positions
    int k = 0;
 
    // Checking for when the string
    // starts with "0"
    for (int i = 0; i < N; i++) {
        if (s[i] == '0') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_0 += abs(k - i);
            k += 2;
        }
    }
 
    // Returning the answer based on
    // the conditions when string
    // length is even
    if (N % 2 == 0)
        return min(ans_1, ans_0);
 
    // When string length is odd
    else {
 
        // When no of ones is greater
        // than no of zeros
        if (ones > zeros)
            return ans_1;
 
        // When no of ones is greater
        // than no of zeros
        else
            return ans_0;
    }
}
 
// Driver Code
int main()
{
    string S = "110100";
    cout << minSwaps(S);
 
    return 0;
}


Java
// Java program for the above approach
 
import java.util.*;
 
class GFG{
 
// Function to find the minimum number
// of adjacent swaps to make the String
// alternating
static int minSwaps(String s)
{
    // Count the no of zeros and ones
    int ones = 0, zeros = 0;
    int N = s.length();
 
    for (int i = 0; i < N; i++) {
        if (s.charAt(i) == '1')
            ones++;
        else
            zeros++;
    }
 
    // Base Case
    if ((N % 2 == 0 && ones != zeros)
        || (N % 2 == 1
            && Math.abs(ones - zeros) != 1)) {
        return -1;
    }
 
    // Store no of min swaps when
    // String starts with "1"
    int ans_1 = 0;
 
    // Keep track of the odd positions
    int j = 0;
 
    // Checking for when the String
    // starts with "1"
    for (int i = 0; i < N; i++) {
        if (s.charAt(i) == '1') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_1 += Math.abs(j - i);
            j += 2;
        }
    }
 
    // Store no of min swaps when String
    // starts with "0"
    int ans_0 = 0;
 
    // Keep track of the odd positions
    int k = 0;
 
    // Checking for when the String
    // starts with "0"
    for (int i = 0; i < N; i++) {
        if (s.charAt(i) == '0') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_0 += Math.abs(k - i);
            k += 2;
        }
    }
 
    // Returning the answer based on
    // the conditions when String
    // length is even
    if (N % 2 == 0)
        return Math.min(ans_1, ans_0);
 
    // When String length is odd
    else {
 
        // When no of ones is greater
        // than no of zeros
        if (ones > zeros)
            return ans_1;
 
        // When no of ones is greater
        // than no of zeros
        else
            return ans_0;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "110100";
    System.out.print(minSwaps(S));
 
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python 3 program for the above approach
 
# Function to find the minimum number
# of adjacent swaps to make the string
# alternating
def minSwaps(s):
   
    # Count the no of zeros and ones
    ones = 0
    zeros = 0
    N = len(s)
 
    for i in range(N):
        if s[i] == '1':
            ones += 1
        else:
            zeros += 1
 
    # Base Case
    if ((N % 2 == 0 and ones != zeros) or (N % 2 == 1 and abs(ones - zeros) != 1)):
        return -1
 
    # Store no of min swaps when
    # string starts with "1"
    ans_1 = 0
 
    # Keep track of the odd positions
    j = 0
 
    # Checking for when the string
    # starts with "1"
    for i in range(N):
        if (s[i] == '1'):
            # Adding the no of swaps to
            # fix "1" at odd positions
            ans_1 += abs(j - i)
            j += 2
 
    # Store no of min swaps when string
    # starts with "0"
    ans_0 = 0
 
    # Keep track of the odd positions
    k = 0
 
    # Checking for when the string
    # starts with "0"
    for i in range(N):
        if(s[i] == '0'):
 
            # Adding the no of swaps to
            # fix "1" at odd positions
            ans_0 += abs(k - i)
            k += 2
 
    # Returning the answer based on
    # the conditions when string
    # length is even
    if (N % 2 == 0):
        return min(ans_1, ans_0)
 
    # When string length is odd
    else:
 
        # When no of ones is greater
        # than no of zeros
        if (ones > zeros):
            return ans_1
 
        # When no of ones is greater
        # than no of zeros
        else:
            return ans_0
 
# Driver Code
if __name__ == '__main__':
    S = "110100"
    print(minSwaps(S))
     
    # This code is contributed by ipg2016107.


C#
// C# program for the above approach
using System;
class GFG{
 
// Function to find the minimum number
// of adjacent swaps to make the String
// alternating
static int minSwaps(String s)
{
    // Count the no of zeros and ones
    int ones = 0, zeros = 0;
    int N = s.Length;
 
    for (int i = 0; i < N; i++) {
        if (s[i] == '1')
            ones++;
        else
            zeros++;
    }
 
    // Base Case
    if ((N % 2 == 0 && ones != zeros)
        || (N % 2 == 1
            && Math.Abs(ones - zeros) != 1)) {
        return -1;
    }
 
    // Store no of min swaps when
    // String starts with "1"
    int ans_1 = 0;
 
    // Keep track of the odd positions
    int j = 0;
 
    // Checking for when the String
    // starts with "1"
    for (int i = 0; i < N; i++) {
        if (s[i] == '1') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_1 += Math.Abs(j - i);
            j += 2;
        }
    }
 
    // Store no of min swaps when String
    // starts with "0"
    int ans_0 = 0;
 
    // Keep track of the odd positions
    int k = 0;
 
    // Checking for when the String
    // starts with "0"
    for (int i = 0; i < N; i++) {
        if (s[i] == '0') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_0 += Math.Abs(k - i);
            k += 2;
        }
    }
 
    // Returning the answer based on
    // the conditions when String
    // length is even
    if (N % 2 == 0)
        return Math.Min(ans_1, ans_0);
 
    // When String length is odd
    else {
 
        // When no of ones is greater
        // than no of zeros
        if (ones > zeros)
            return ans_1;
 
        // When no of ones is greater
        // than no of zeros
        else
            return ans_0;
    }
}
 
// Driver Code
public static void Main()
{
    String S = "110100";
    Console.WriteLine(minSwaps(S));
 
}
}
 
// This code is contributed by ihritik


Javascript



输出:
2

时间复杂度: O(N)
辅助空间: O(1)