📌  相关文章
📜  通过字符的 ASCII 值的最小增量或减量使字符串的所有字符相同

📅  最后修改于: 2021-09-03 03:45:26             🧑  作者: Mango

给定长度为N的字符串S ,任务是通过将任何字符的 ASCII 值递增/递减1任意次数来使字符串的所有字符相同。
注意:所有字符必须改为原字符串的一个字符。

例子:

原始的方法:要解决这个问题最简单的办法是遍历字符串,并为每个不同的字符,计算使字符串相同字符的所有字符所需操作的总数。最后,打印任何字符所需的最少操作次数。
时间复杂度: O(N 2 )
辅助空间: O(1)

有效的方法:可以通过观察只有当字符等于已排序字符串中的中间字符时才能获得最少操作次数来优化上述方法。
请按照以下步骤解决问题:

  • 以非降序对字符串的字符进行排序。
  • 现在,为了使所有的字符操作的最小数量相等,使字符等于字符在排序字符串中间。
  • 发现在已排序字符串中间中旬= S [N / 2]的字符。
  • 初始化一个变量,比如total_operations ,以存储使字符串的所有字符相等所需的最小操作数。
  • 遍历字符串,对于遇到的每个字符,通过添加当前字符和mid的绝对差来更新total_operations
  • 打印total_operations作为所需的最小操作数。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check if all characters
// of the string can be made the same
int sameChar(string S, int N)
{
 
    // Sort the string
    sort(S.begin(), S.end());
 
    // Calculate ASCII value
    // of the median character
    int mid = S[N / 2];
 
    // Stores the minimum number of
    // operations required to make
    // all characters equal
    int total_operations = 0;
 
    // Traverse the string
    for (int i = 0; i < N; i++) {
 
        // Calculate absolute value of
        // current character and median character
        total_operations
            += abs(int(S[i]) - mid);
    }
 
    // Print the minimum number of
    // operations required
    cout << total_operations;
}
 
// Driver Code
int main()
{
    string S = "geeks";
    int N = S.size();
 
    sameChar(S, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.Arrays;
class GFG {
 
  // Function to check if all characters
  // of the string can be made the same
  static void sameChar(String S, int N)
  {
 
    char temp[] = S.toCharArray();
 
    // Sort the string
    Arrays.sort(temp);
 
    String s = new String(temp);
 
    // Calculate ASCII value
    // of the median character
    int mid = s.charAt(N / 2);
 
    // Stores the minimum number of
    // operations required to make
    // all characters equal
    int total_operations = 0;
 
    // Traverse the string
    for (int i = 0; i < N; i++) {
 
      // Calculate absolute value of
      // current character and median character
      total_operations
        += Math.abs(((s.charAt(i) - 0) - mid));
    }
 
    // Print the minimum number of
    // operations required
    System.out.print(total_operations);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String S = "geeks";
    int N = S.length();
 
    sameChar(S, N);
  }
}
 
// This code is contributed by Dharanendra L V.


Python3
# Python program for the above approach
 
# Function to check if all characters
# of the string can be made the same
def sameChar(S, N):
 
    # Sort the string
    S = ''.join(sorted(S))
 
    # Calculate ASCII value
    # of the median character
    mid = ord(S[N // 2])
 
    # Stores the minimum number of
    # operations required to make
    # all characters equal
    total_operations = 0
 
    # Traverse the string
    for i in range(N):
 
        # Calculate absolute value of
        # current character and median character
        total_operations += abs(ord(S[i]) - mid)
 
    # Print the minimum number of
    # operations required
    print(total_operations)
 
# Driver Code
S = "geeks"
N = len(S)
sameChar(S, N)
 
# This code is contributed by subhammahato348.


C#
// C# program for the above approach
using System;
public class GFG {
 
  // Function to check if all characters
  // of the string can be made the same
  static void sameChar(String S, int N)
  {
 
    char[] temp = S.ToCharArray();
 
    // Sort the string
    Array.Sort(temp);
 
    String s = new String(temp);
 
    // Calculate ASCII value
    // of the median character
    int mid = s[N / 2];
 
    // Stores the minimum number of
    // operations required to make
    // all characters equal
    int total_operations = 0;
 
    // Traverse the string
    for (int i = 0; i < N; i++) {
 
      // Calculate absolute value of
      // current character and median character
      total_operations += Math.Abs((s[i] - 0) - mid);
    }
 
    // Print the minimum number of
    // operations required
    Console.Write(total_operations);
  }
 
  // Driver Code
  static public void Main()
  {
 
    String S = "geeks";
    int N = S.Length;
 
    sameChar(S, N);
  }
}
 
// This code is contributed by Dharanendra L V.


Javascript


输出:
20

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live