📌  相关文章
📜  将相似字符组合在一起的最小相邻交换次数

📅  最后修改于: 2021-10-26 05:38:14             🧑  作者: Mango

给定一个长度为N的字符串S ,仅由小写英文字符,任务是找到将相同字符组合在一起所需的最小相邻交换数。

例子:

方法:想法是存储每个字符的索引。然后,对于每个字符,找到相邻的绝对差异并将它们添加到答案中。请按照以下步骤解决问题:

  1. 初始化一个二维向量arr[] ,其中向量arr[i]将存储字符(i + ‘a’)的索引和一个初始化为0的变量answer
  2. [0, N – 1]范围内迭代给定的字符串。
  3. 将索引i添加到arr[S[i] – ‘a’]
  4. 遍历字符串,从i = ‘a’‘z’遍历二维向量arr[]
  5. 对于每个字符i ,找出该向量中出现的字符i的索引的绝对相邻差,并将它们添加到答案中
  6. 遍历二维向量后,将答案打印为最小交换次数。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find minimum adjacent
// swaps required to make all the
// same character adjacent
int minSwaps(string S, int n)
{
    // Initialize answer
    int swaps = 0;
 
    // Create a 2D array of size 26
    vector > arr(26);
 
    // Traverse the string
    for (int i = 0; i < n; i++) {
 
        // Get character
        int pos = S[i] - 'a';
 
        // Append the current index in
        // the corresponding vector
        arr[pos].push_back(i);
    }
 
    // Traverse each character from a to z
    for (char ch = 'a'; ch <= 'z'; ++ch) {
        int pos = ch - 'a';
 
        // Add difference of adjacent index
        for (int i = 1;
             i < arr[pos].size(); ++i) {
 
            swaps += abs(arr[pos][i]
                         - arr[pos][i - 1] - 1);
        }
    }
 
    // Return answer
    return swaps;
}
 
// Driver Code
int main()
{
    // Given string
    string S = "abbccabbcc";
 
    // Size of string
    int N = S.length();
 
    // Function Call
    cout << minSwaps(S, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find minimum adjacent
// swaps required to make all the
// same character adjacent
static int minSwaps(String S, int n)
{
     
    // Initialize answer
    int swaps = 0;
 
    // Create a 2D array of size 26
    @SuppressWarnings("unchecked")
    Vector []arr = new Vector[26];
    for(int i = 0; i < arr.length; i++)
        arr[i] = new Vector();
         
    // Traverse the String
    for(int i = 0; i < n; i++)
    {
         
        // Get character
        int pos = S.charAt(i) - 'a';
 
        // Append the current index in
        // the corresponding vector
        arr[pos].add(i);
    }
 
    // Traverse each character from a to z
    for(char ch = 'a'; ch <= 'z'; ++ch)
    {
        int pos = ch - 'a';
 
        // Add difference of adjacent index
        for(int i = 1; i < arr[pos].size(); ++i)
        {
            swaps += Math.abs(arr[pos].get(i) -
                              arr[pos].get(i - 1) - 1);
        }
    }
 
    // Return answer
    return swaps;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given String
    String S = "abbccabbcc";
 
    // Size of String
    int N = S.length();
 
    // Function Call
    System.out.print(minSwaps(S, N));
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach
 
# Function to find minimum adjacent
# swaps required to make all the
# same character adjacent
def minSwaps(S, n):
     
    # Initialize answer
    swaps = 0
 
    # Create a 2D array of size 26
    arr = [[] for i in range(26)]
 
    # Traverse the string
    for i in range(n):
         
        # Get character
        pos = ord(S[i]) - ord('a')
 
        # Append the current index in
        # the corresponding vector
        arr[pos].append(i)
 
    # Traverse each character from a to z
    for ch in range(ord('a'), ord('z') + 1):
        pos = ch - ord('a')
 
        # Add difference of adjacent index
        for i in range(1, len(arr[pos])):
            swaps += abs(arr[pos][i] -
                         arr[pos][i - 1] - 1)
 
    # Return answer
    return swaps
 
# Driver Code
if __name__ == '__main__':
     
    # Given string
    S = "abbccabbcc"
 
    # Size of string
    N = len(S)
 
    # Function Call
    print(minSwaps(S, N))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find minimum
// adjacent swaps required
// to make all the same
// character adjacent
static int minSwaps(String S,
                    int n)
{   
  // Initialize answer
  int swaps = 0;
 
  // Create a 2D array
  // of size 26
  List []arr =
       new List[26];
   
  for(int i = 0;
          i < arr.Length; i++)
    arr[i] = new List();
 
  // Traverse the String
  for(int i = 0; i < n; i++)
  {
    // Get character
    int pos = S[i] - 'a';
 
    // Append the current index in
    // the corresponding vector
    arr[pos].Add(i);
  }
 
  // Traverse each character
  // from a to z
  for(char ch = 'a';
           ch <= 'z'; ++ch)
  {
    int pos = ch - 'a';
 
    // Add difference of
    // adjacent index
    for(int i = 1;
            i < arr[pos].Count; ++i)
    {
      swaps += Math.Abs(arr[pos][i] -
                        arr[pos][i - 1] - 1);
    }
  }
 
  // Return answer
  return swaps;
}
 
// Driver Code
public static void Main(String[] args)
{   
  // Given String
  String S = "abbccabbcc";
 
  // Size of String
  int N = S.Length;
 
  // Function Call
  Console.Write(minSwaps(S, N));
}
}
 
// This code is contributed by gauravrajput1


Javascript


输出
10

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程