📌  相关文章
📜  给定字符串中要替换的最少字符以使所有字符相同

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

给定字符串中要替换的最少字符以使所有字符相同

给定一个大小为N的由小写英文字符组成的字符串str ,任务是找到要替换的最小字符以使字符串str的所有字符相同。任何字符都可以替换为任何其他字符。

例子:

做法:为了使所有字符相同而需要替换的最小字符数基本上是不等于最频繁字符的字符数,即N-(最频繁字符的频率) 。现在按照以下步骤解决此问题:

  1. 将所有字符的频率存储在向量频率
  2. 找到最大频率mxfreq
  3. 返回 ( N – mxfreq)作为答案。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the minimum characters
// to be replaced to make all characters
// of string str same
int minCost(char* word, int N)
{
    int mxfreq = 0;
    vector freq(26, 0);
 
    for (int i = 0; i < strlen(word); i++) {
        freq[word[i] - 'a']++;
        mxfreq = max(mxfreq,
                     freq[word[i] - 'a']);
    }
 
    return N - mxfreq;
}
 
// Driver Code
int main()
{
    char str[] = "data";
    int N = sizeof(str) / sizeof(char);
 
    cout << minCost(str, N - 1);
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
   
// Function to find the minimum characters
// to be replaced to make all characters
// of string str same
static int minCost(String word, int N)
{
    int mxfreq = 0;
    int[] freq = new int[26];
 
    for (int i = 0; i < N; i++) {
          char ch = word.charAt(i);
        freq[ch - 'a']++;
        mxfreq = Math.max(mxfreq, freq[ch - 'a']);
    }
 
    return N - mxfreq;
}
 
    public static void main (String[] args) {
      
           String str = "data";
        int N = str.length();
        System.out.println(minCost(str, N - 1));
    }
}
 
// This code is contributed by hrithikgarg03188


Python3
# Python code for the above approach
 
# Function to find the minimum characters
# to be replaced to make all characters
# of string str same
def minCost(word, N):
    mxfreq = 0;
    freq = [0] * 26
    for i in range(len(word)):
        freq[ord(word[i]) - ord('a')] = freq[ord(word[i]) - ord('a')] + 1;
        mxfreq = max(mxfreq, freq[ord(word[i]) -  ord('a')]);
    return N - mxfreq + 1;
 
# Driver Code
str = "data";
N = len(str)
 
print(minCost(str, N - 1));
 
# This code is contributed by Saurabh Jaiswal


C#
// C# program for the above approach
using System;
class GFG
{
 
  // Function to find the minimum characters
  // to be replaced to make all characters
  // of string str same
  static int minCost(string word, int N)
  {
    int mxfreq = 0;
    int[] freq = new int[26];
 
    for (int i = 0; i < N; i++) {
      char ch = word[i];
      freq[ch - 'a']++;
      mxfreq = Math.Max(mxfreq, freq[ch - 'a']);
    }
 
    return N - mxfreq;
  }
 
  // Driver code
  public static void Main ()
  {
 
    string str = "data";
    int N = str.Length;
    Console.WriteLine(minCost(str, N - 1));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript



输出
2

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