📌  相关文章
📜  最大限度地降低按字符频率升序对字符串进行排序的成本

📅  最后修改于: 2021-05-07 04:40:07             🧑  作者: Mango

给定字符串S ,任务是通过将一个重复字符块与另一个不同重复字符块交换来计算以最低频率对字符串进行排序的最低成本。每次操作的成本是两个模块的绝对差。
例子:

方法:
请按照以下步骤解决问题:

  • 存储出现在字符串中的每个字符的频率。
  • 对频率进行排序。
  • 计算已排序序列和原始序列中每个频率之间的差异。
  • 所有差异的总和的一半是必需的答案。这是因为,对于每个交换,在上面的步骤中两次计算出差额。

下面是上述方法的实现:

C++
// C++ program to implement
// above approach
#include 
using namespace std;
 
int sortString(string S)
{
    vector sorted, original;
    bool insert = false;
     
    // For a single character
    if (S.length() == 1)
    {
        cout << 0 << endl;
    }
     
    // Stores count of repetitions
    // of a character
    int curr = 1;
     
    for(int i = 0; i < (S.length() - 1); i++)
    {
         
        // If repeating character
        if (S[i] == S[i + 1])
        {
            curr += 1;
            insert = false;
        }
         
        // Otherwise
        else
        {
         
            // Store frequency
            sorted.push_back(curr);
            original.push_back(curr);
             
            // Reset count
            curr = 1;
            insert = true;
        }
    }
     
    // Insert the last character block
    if ((S[(S.length() - 1)] !=
         S[(S.length() - 2)]) || insert == false)
    {
        sorted.push_back(curr);
        original.push_back(curr);
    }
     
    // Sort the frequencies
    sort(sorted.begin(), sorted.end());
     
    // Stores the minimum cost of all operations
    int t_cost = 0;
     
    for(int i = 0; i < sorted.size(); i++)
    {
         
        // Store the absolute difference of
        // i-th frequencies of ordered and
        // unordered sequences
        t_cost += abs(sorted[i] -
                      original[i]);
    }
     
    // Return the minimum cost
    return (t_cost / 2);
}
           
// Driver Code
int main()
{
    string S = "aabbcccdeffffggghhhhhii";
     
    cout << sortString(S);
     
    return 0;
}


Java
// Java program to implement
// above approach
import java.util.*;
 
class GFG{
 
public static int sortString(String S)
{
    Vector sorted = new Vector();
    Vector original = new Vector();
    boolean insert = false;
     
    // For a single character
    if (S.length() == 1)
    {
        System.out.println(0);
    }
     
    // Stores count of repetitions
    // of a character
    int curr = 1;
    for(int i = 0; i < (S.length() - 1); i++)
    {
         
        // If repeating character
        if (S.charAt(i) == S.charAt(i + 1))
        {
            curr += 1;
            insert = false;
        }
         
        // Otherwise
        else
        {
             
            // Store frequency
            sorted.add(curr);
            original.add(curr);
             
            // Reset count
            curr = 1;
            insert = true;
        }
    }
     
    // Insert the last character block
    if ((S.charAt(S.length() - 1) !=
         S.charAt(S.length() - 2)) ||
         insert == false)
    {
        sorted.add(curr);
        original.add(curr);
    }
     
    // Sort the frequencies
    Collections.sort(sorted);
     
    // Stores the minimum cost of all operations
    int t_cost = 0;
    for(int i = 0; i < sorted.size(); i++)
    {
         
        // Store the absolute difference of
        // i-th frequencies of ordered and
        // unordered sequences
        t_cost += Math.abs(sorted.get(i) -
                           original.get(i));
    }
     
    // Return the minimum cost
    return (t_cost / 2);
}
 
// Driver code
public static void main(String[] args)
{
    String S = "aabbcccdeffffggghhhhhii";
    System.out.print(sortString(S));
}
}
  
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program to implement
# the above approach
def sortString(S):
   
    sorted1 = []
    original = []
    insert = False
 
    # For a single character
    if (len(S) == 1):
        print(0)
 
    # Stores count of repetitions
    # of a character
    curr = 1
 
    for i in range(len(S) - 1):
        # If repeating character
        if (S[i] == S[i + 1]):
            curr += 1
            insert = False
 
        # Otherwise
        else:
            # Store frequency
            sorted1.append(curr)
            original.append(curr)
 
            # Reset count
            curr = 1
            insert = True
 
    # Insert the last character block
    if ((S[(len(S) - 1)] != S[(len(S) - 2)]) or
         insert == False):
        sorted1.append(curr)
        original.append(curr)
 
    # Sort the frequencies
    sorted1.sort()
 
    # Stores the minimum cost of all operations
    t_cost = 0
 
    for i in range(len(sorted1)):
       
        # Store the absolute difference of
        # i-th frequencies of ordered and
        # unordered sequences
        t_cost += abs(sorted1[i] - original[i])
 
    # Return the minimum cost
    return (t_cost // 2)
 
# Driver Code
if __name__ == "__main__":
    S = "aabbcccdeffffggghhhhhii"
    print(sortString(S))
 
# This code is contributed by Chitranayal


C#
// C# program to implement
// above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
public static int sortString(string S)
{
    List sorted = new List();
    List original = new List();
     
    bool insert = false;
  
    // For a single character
    if (S.Length == 1)
    {
        Console.WriteLine(0);
    }
  
    // Stores count of repetitions
    // of a character
    int curr = 1;
  
    for(int i = 0; i < (S.Length - 1); i++)
    {
         
        // If repeating character
        if (S[i] == S[i + 1])
        {
            curr += 1;
            insert = false;
        }
         
        // Otherwise
        else
        {
             
            // Store frequency
            sorted.Add(curr);
            original.Add(curr);
             
            // Reset count
            curr = 1;
            insert = true;
        }
    }
     
    // Insert the last character block
    if ((S[S.Length - 1] !=
         S[S.Length - 2]) || insert == false)
    {
        sorted.Add(curr);
        original.Add(curr);
    }
  
    // Sort the frequencies
    sorted.Sort();
  
    // Stores the minimum cost of all operations
    int t_cost = 0;
  
    for(int i = 0; i < sorted.Count; i++)
    {
         
        // Store the absolute difference of
        // i-th frequencies of ordered and
        // unordered sequences
        t_cost += Math.Abs(sorted[i] -
                         original[i]);
    }
     
    // Return the minimum cost
    return (t_cost / 2);
}
 
// Driver Code   
static void Main()
{
    string S = "aabbcccdeffffggghhhhhii";
     
    Console.Write(sortString(S));
}
}
 
// This code is contributed by divyesh072019


Javascript


输出:
5

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