📌  相关文章
📜  最小化所需的字符对交换,以使字符串中没有两个相邻的字符相同

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

最小化所需的字符对交换,以使字符串中没有两个相邻的字符相同

给定一个由N个字符组成的字符串S ,任务是找到需要交换的最小字符对数,使得没有两个相邻字符相同。如果无法这样做,则打印“-1”

例子:

方法:给定的问题可以通过使用回溯来解决。这个想法是生成一对索引交换的所有可能组合,然后如果生成的字符串没有与最小交换相同的相邻字符,则打印执行的最小交换操作数。请按照以下步骤解决问题:

  • 定义一个函数minimumSwaps(字符串 &str, int &minimumSwaps, int swaps=0, int idx)并执行以下操作:
    • 如果字符串str的相邻字符不同,则将 minimumSwaps 的值更新为minimumSwapsswaps最小值
    • 使用变量i遍历范围[idx, N]并执行以下操作:
      • 使用变量j迭代范围[i + 1, N]并执行以下操作:
        • 交换字符串Sij位置的字符。
        • 调用函数minimumSwaps(str, minimumSwaps, swaps+1, i + 1)以查找其他可能的交换对以生成结果字符串。
        • 交换字符Sij位置的字符串。
  • 初始化变量,比如ansSwapsINT_MAX以存储所需的最小交换计数。
  • 调用函数minimumSwaps(str, ansSwaps)找到使所有相邻字符不同所需的最小交换次数。
  • 完成上述步骤后,如果ansSwaps的值为INT_MAX,则打印-1 。否则,打印ansSwaps的值作为结果最小交换。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check if S
// contains any pair of
// adjacent characters that are same
bool check(string& S)
{
    // Traverse the string S
    for (int i = 1; i < S.length(); i++) {
 
        // If current pair of adjacent
        // characters are the same
        if (S[i - 1] == S[i]) {
            return false;
        }
    }
 
    // Return true
    return true;
}
 
// Utility function to find the minimum number
// of swaps of pair of characters required
// to make all pairs of adjacent characters different
void minimumSwaps(string& S, int& ansSwaps,
                  int swaps = 0, int idx = 0)
{
    // Check if the required string
    // is formed already
    if (check(S)) {
        ansSwaps = min(ansSwaps, swaps);
    }
 
    // Traverse the string S
    for (int i = idx;
         i < S.length(); i++) {
 
        for (int j = i + 1;
             j < S.length(); j++) {
 
            // Swap the characters at i
            // and j position
            swap(S[i], S[j]);
            minimumSwaps(S, ansSwaps,
                         swaps + 1, i + 1);
 
            // Swap for Backtracking
            // Step
            swap(S[i], S[j]);
        }
    }
}
 
// Function to find the minimum number
// of swaps of pair of characters required
// to make all pairs of adjacent characters different
void findMinimumSwaps(string& S)
{
 
    // Stores the resultant minimum
    // number of swaps required
    int ansSwaps = INT_MAX;
 
    // Function call to find the
    // minimum swaps required
    minimumSwaps(S, ansSwaps);
 
    // Print the result
    if (ansSwaps == INT_MAX)
        cout << "-1";
    else
        cout << ansSwaps;
}
 
// Driver Code
int main()
{
    string S = "ABAACD";
    findMinimumSwaps(S);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG
{
    static int ansSwaps ;
   
// Function to check if S
// contains any pair of
// adjacent characters that are same
static boolean check(char[] S)
{
   
    // Traverse the String S
    for (int i = 1; i < S.length; i++) {
 
        // If current pair of adjacent
        // characters are the same
        if (S[i - 1] == S[i]) {
            return false;
        }
    }
 
    // Return true
    return true;
}
 
// Utility function to find the minimum number
// of swaps of pair of characters required
// to make all pairs of adjacent characters different
static void minimumSwaps(char[] S,
                  int swaps, int idx)
{
   
    // Check if the required String
    // is formed already
    if (check(S)) {
        ansSwaps = Math.min(ansSwaps, swaps);
    }
 
    // Traverse the String S
    for (int i = idx;
         i < S.length; i++) {
 
        for (int j = i + 1;
             j < S.length; j++) {
 
            // Swap the characters at i
            // and j position
            swap(S,i,j);
            minimumSwaps(S,
                         swaps + 1, i + 1);
 
            // Swap for Backtracking
            // Step
            S= swap(S,i,j);
        }
    }
}
static char[] swap(char []arr, int i, int j){
    char temp= arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
    return arr;
}
   
// Function to find the minimum number
// of swaps of pair of characters required
// to make all pairs of adjacent characters different
static void findMinimumSwaps(char[] S)
{
 
    // Stores the resultant minimum
    // number of swaps required
    ansSwaps = Integer.MAX_VALUE;
 
    // Function call to find the
    // minimum swaps required
    minimumSwaps(S, 0,0);
 
    // Print the result
    if (ansSwaps == Integer.MAX_VALUE)
        System.out.print("-1");
    else
        System.out.print(ansSwaps);
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "ABAACD";
    findMinimumSwaps(S.toCharArray());
 
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
import sys
ansSwaps = 0
 
# Function to check if S
# contains any pair of
# adjacent characters that are same
def check(S):
   
    # Traverse the String S
    for i in range(1, len(S)):
       
        # If current pair of adjacent
        # characters are the same
        if (S[i - 1] == S[i]):
            return False
  
    # Return true
    return True
  
# Utility function to find the minimum number
# of swaps of pair of characters required
# to make all pairs of adjacent characters different
def minimumSwaps(S, swaps , idx):
    global ansSwaps
     
    # Check if the required String
    # is formed already
    if (check(S)):
        ansSwaps = 1+min(ansSwaps, swaps)
  
    # Traverse the String S
    for i in range(idx, len(S)):
        for j in range(i + 1, len(S)):
           
            # Swap the characters at i
            # and j position
            swap(S, i, j)
            minimumSwaps(S, swaps + 1, i + 1)
  
            # Swap for Backtracking
            # Step
            S = swap(S, i, j)
  
def swap(arr , i , j):
    temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
    return arr
    
# Function to find the minimum number
# of swaps of pair of characters required
# to make all pairs of adjacent characters different
def findMinimumSwaps(S):
    global ansSwaps
     
    # Stores the resultant minimum
    # number of swaps required
    ansSwaps = sys.maxsize
  
    # Function call to find the
    # minimum swaps required
    minimumSwaps(S, 0,0)
  
    # Print the result
    if (ansSwaps == sys.maxsize):
        print("-1")
    else:
        print(ansSwaps)
 
S = "ABAACD"
findMinimumSwaps(S.split())
 
# This code is contributed by rameshtravel07.


C#
// C# program for the above approach
using System;
 
public class GFG
{
    static int ansSwaps ;
   
// Function to check if S
// contains any pair of
// adjacent characters that are same
static bool check(char[] S)
{
   
    // Traverse the String S
    for (int i = 1; i < S.Length; i++) {
 
        // If current pair of adjacent
        // characters are the same
        if (S[i - 1] == S[i]) {
            return false;
        }
    }
 
    // Return true
    return true;
}
 
// Utility function to find the minimum number
// of swaps of pair of characters required
// to make all pairs of adjacent characters different
static void minimumSwaps(char[] S,
                  int swaps, int idx)
{
   
    // Check if the required String
    // is formed already
    if (check(S)) {
        ansSwaps = Math.Min(ansSwaps, swaps);
    }
 
    // Traverse the String S
    for (int i = idx;
         i < S.Length; i++) {
 
        for (int j = i + 1;
             j < S.Length; j++) {
 
            // Swap the characters at i
            // and j position
            swap(S,i,j);
            minimumSwaps(S,
                         swaps + 1, i + 1);
 
            // Swap for Backtracking
            // Step
            S= swap(S,i,j);
        }
    }
}
static char[] swap(char []arr, int i, int j){
    char temp= arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
    return arr;
}
   
// Function to find the minimum number
// of swaps of pair of characters required
// to make all pairs of adjacent characters different
static void findMinimumSwaps(char[] S)
{
 
    // Stores the resultant minimum
    // number of swaps required
    ansSwaps = int.MaxValue;
 
    // Function call to find the
    // minimum swaps required
    minimumSwaps(S, 0,0);
 
    // Print the result
    if (ansSwaps == int.MaxValue)
        Console.Write("-1");
    else
        Console.Write(ansSwaps);
}
 
// Driver Code
public static void Main(String[] args)
{
    String S = "ABAACD";
    findMinimumSwaps(S.ToCharArray());
 
}
}
 
// This code is contributed by 29AjayKumar.


Javascript


输出:
1

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