📌  相关文章
📜  需要删除的最少字符才能使每个字符的频率唯一

📅  最后修改于: 2021-10-27 16:56:58             🧑  作者: Mango

字符串str,任务是找到需要从字符串,使得字符串的每个字符的频率是独特删除的最少字符数。

例子:

方法:该问题可以使用贪心技术解决。这个想法是使用 Map 和 Priority Queue。请按照以下步骤解决问题:

  • 初始化一个 Map,比如mp ,以存储字符串的每个不同字符的频率。
  • 初始化一个变量,比如cntChar来存储需要删除的字符数,以使字符串中每个字符的频率唯一。
  • 创建一个 priority_queue,比如说pq来存储每个字符的频率,这样获得的最大频率出现在优先级队列pq的顶部。
  • 遍历priority_queue直到PQ是空的,并检查是否最上面的PQ的元素的是等于或PQ不的第二顶端元件。如果发现为真,则将pq的最顶层元素的值递减1并将cntChar的值递增1
  • 否则,弹出 pq 的最顶层元素。
  • 最后,打印cntChar的值。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to find the minimum count of
// characters required to be deleted to make
// frequencies of all characters unique
int minCntCharDeletionsfrequency(string& str,
                                 int N)
{
    // Stores frequency of each
    // distinct character of str
    unordered_map mp;
 
    // Store frequency of each distinct
    // character such that the largest
    // frequency is present at the top
    priority_queue pq;
 
    // Stores minimum count of characters
    // required to be deleted to make
    // frequency of each character unique
    int cntChar = 0;
 
    // Traverse the string
    for (int i = 0; i < N; i++) {
 
        // Update frequency of str[i]
        mp[str[i]]++;
    }
 
    // Traverse the map
    for (auto it : mp) {
 
        // Insert current
        // frequency into pq
        pq.push(it.second);
    }
 
    // Traverse the priority_queue
    while (!pq.empty()) {
 
        // Stores topmost
        // element of pq
        int frequent
            = pq.top();
 
        // Pop the topmost element
        pq.pop();
 
        // If pq is empty
        if (pq.empty()) {
 
            // Return cntChar
            return cntChar;
        }
 
        // If frequent and topmost
        // element of pq are equal
        if (frequent == pq.top()) {
 
            // If frequency of the topmost
            // element is greater than 1
            if (frequent > 1) {
 
                // Insert the decremented
                // value of frequent
                pq.push(frequent - 1);
            }
 
            // Update cntChar
            cntChar++;
        }
    }
 
    return cntChar;
}
 
// Driver Code
int main()
{
 
    string str = "abbbcccd";
 
    // Stores length of str
    int N = str.length();
    cout << minCntCharDeletionsfrequency(
        str, N);
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to find the minimum count of
// characters required to be deleted to make
// frequencies of all characters unique
static int minCntCharDeletionsfrequency(char[] str,
                                        int N)
{
  // Stores frequency of each
  // distinct character of str
  HashMap mp =
          new HashMap<>();
 
  // Store frequency of each distinct
  // character such that the largest
  // frequency is present at the top
  PriorityQueue pq =
          new PriorityQueue<>((x, y) ->
          Integer.compare(y, x));
 
  // Stores minimum count of characters
  // required to be deleted to make
  // frequency of each character unique
  int cntChar = 0;
 
  // Traverse the String
  for (int i = 0; i < N; i++)
  {
    // Update frequency of str[i]
    if(mp.containsKey(str[i]))
    {
      mp.put(str[i],
      mp.get(str[i]) + 1);
    }
    else
    {
      mp.put(str[i], 1);
    }
  }
 
  // Traverse the map
  for (Map.Entry it :
                 mp.entrySet())
  {
    // Insert current
    // frequency into pq
    pq.add(it.getValue());
  }
 
  // Traverse the priority_queue
  while (!pq.isEmpty())
  {
    // Stores topmost
    // element of pq
    int frequent = pq.peek();
 
    // Pop the topmost element
    pq.remove();
 
    // If pq is empty
    if (pq.isEmpty()) {
 
      // Return cntChar
      return cntChar;
    }
 
    // If frequent and topmost
    // element of pq are equal
    if (frequent == pq.peek())
    {
      // If frequency of the topmost
      // element is greater than 1
      if (frequent > 1)
      {
        // Insert the decremented
        // value of frequent
        pq.add(frequent - 1);
      }
 
      // Update cntChar
      cntChar++;
    }
  }
 
  return cntChar;
}
 
// Driver Code
public static void main(String[] args)
{
  String str = "abbbcccd";
 
  // Stores length of str
  int N = str.length();
  System.out.print(minCntCharDeletionsfrequency(
         str.toCharArray(), N));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program to implement
# the above approach
 
# Function to find the minimum count of
# characters required to be deleted to make
# frequencies of all characters unique
def minCntCharDeletionsfrequency(str, N):
     
    # Stores frequency of each
    # distinct character of str
    mp = {}
 
    # Store frequency of each distinct
    # character such that the largest
    # frequency is present at the top
    pq = []
 
    # Stores minimum count of characters
    # required to be deleted to make
    # frequency of each character unique
    cntChar = 0
 
    # Traverse the string
    for i in range(N):
         
        # Update frequency of str[i]
        mp[str[i]] = mp.get(str[i], 0) + 1
         
    # Traverse the map
    for it in mp:
         
        # Insert current
        # frequency into pq
        pq.append(mp[it])
 
    pq = sorted(pq)
     
    # Traverse the priority_queue
    while (len(pq) > 0):
         
        # Stores topmost
        # element of pq
        frequent = pq[-1]
 
        # Pop the topmost element
        del pq[-1]
 
        # If pq is empty
        if (len(pq) == 0):
             
            # Return cntChar
            return cntChar
             
        # If frequent and topmost
        # element of pq are equal
        if (frequent == pq[-1]):
             
            # If frequency of the topmost
            # element is greater than 1
            if (frequent > 1):
                 
                # Insert the decremented
                # value of frequent
                pq.append(frequent - 1)
                 
            # Update cntChar
            cntChar += 1
             
        pq = sorted(pq)
         
    return cntChar
 
# Driver Code
if __name__ == '__main__':
     
    str = "abbbcccd"
 
    # Stores length of str
    N = len(str)
     
    print(minCntCharDeletionsfrequency(str, N))
 
# This code is contributed by mohit kumar 29


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the minimum count of
// characters required to be deleted to make
// frequencies of all characters unique
static int minCntCharDeletionsfrequency(char[] str,
                                        int N)
{
     
    // Stores frequency of each
    // distinct character of str
    Dictionary mp = new Dictionary();
 
    // Store frequency of each distinct
    // character such that the largest
    // frequency is present at the top
    List pq = new List();
 
    // Stores minimum count of characters
    // required to be deleted to make
    // frequency of each character unique
    int cntChar = 0;
 
    // Traverse the String
    for(int i = 0; i < N; i++)
    {
         
        // Update frequency of str[i]
        if (mp.ContainsKey(str[i]))
        {
            mp[str[i]]++;
        }
        else
        {
            mp.Add(str[i], 1);
        }
    }
 
    // Traverse the map
    foreach(KeyValuePair it in mp)
    {
         
        // Insert current
        // frequency into pq
        pq.Add(it.Value);
    }
    pq.Sort();
    pq.Reverse();
     
    // Traverse the priority_queue
    while (pq.Count != 0)
    {
         
        // Stores topmost
        // element of pq
        pq.Sort();
        pq.Reverse();
        int frequent = pq[0];
 
        // Pop the topmost element
        pq.RemoveAt(0);
 
        // If pq is empty
        if (pq.Count == 0)
        {
             
            // Return cntChar
            return cntChar;
        }
 
        // If frequent and topmost
        // element of pq are equal
        if (frequent == pq[0])
        {
             
            // If frequency of the topmost
            // element is greater than 1
            if (frequent > 1)
            {
                 
                // Insert the decremented
                // value of frequent
                pq.Add(frequent - 1);
                pq.Sort();
                // pq.Reverse();
            }
 
            // Update cntChar
            cntChar++;
        }
    }
    return cntChar;
}
 
// Driver Code
public static void Main(String[] args)
{
    String str = "abbbcccd";
 
    // Stores length of str
    int N = str.Length;
     
    Console.Write(minCntCharDeletionsfrequency(
        str.ToCharArray(), N));
}
}
 
// This code is contributed by shikhasingrajput


Javascript


输出:
2

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

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