📜  要选择的最大字符串数,以便有多数字符

📅  最后修改于: 2021-10-26 02:33:04             🧑  作者: Mango

给定一个由N个小写字符字符串组成的数组A[] ,任务是找到最大数量的字符串,使得一个字符占多数,即所有字符串中一个字符的出现次数大于所有其他字符的总和。

例子:

方法:这个问题有一个贪心的解决方案。这个想法是,考虑从‘a’‘z’ 的所有小写字符,对于每个字符,找到可以选择的最大字符串数,以便该字符的出现次数大于所有其他字符的总和。其中最多的将是答案。现在的主要问题是如何找到一个特定字符占多数的最大字符串数,来解决这个使用贪心算法的问题。这个想法是,要找到一个特定的字符“CH”字符串的最大数量尽量选择在与所有其他字符的出现“CH”的发生是最大的字符串,即字符串中( ‘ch’ 的出现 – 所有其他字符的出现次数最多,以便将来可以添加更多字符串。

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

  • 定义一个函数CalDif(字符串 s, char ch)并执行以下任务:
    • 初始化变量chcount0到字符的数量和othercount存储为0存储的其他字符计数。
    • 使用变量x遍历字符串s并执行以下任务:
      • 如果字符在当前位置是CH,然后通过1个,否则增加1个增加chcount价值的othercount
    • 返回chcountothercount之间的差值
  • 初始化变量ans并赋值0 ,它将存储最终答案。
  • 使用变量i迭代小写字符范围[a, z]并执行以下步骤:  
    • 初始化一个长度为N的向量arr[] ,其中arr[i]将为第 i 个字符串存储(ch 的出现 – 所有其他字符)
    • 运行从i=0N-1的循环
      • 对于第i字符串使用函数CalDiff(A[i], ch)计算(ch 的出现 – 所有其他字符的出现并将其分配给arr[i]
    • 按降序对arr[]进行排序。
    • 初始化两个变量tempcount并为它们分配0
    • 遍历数组arr[]并执行temp += arr[i]count++ ,其中i0开始,直到temp <= 0
    • 设置anscountans max 的值。
  • 执行完上述步骤后,打印ans的值作为答案。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate (occurrence of ch -
// occurrence of all other characters combined)
int CalDiff(string s, char ch)
{
    // Initialize ch count as 0
    int chcount = 0;
 
    // Initialize all other char count as 0
    int othercount = 0;
 
    // Traversing the string
    for (auto x : s) {
        // Current character is ch
        if (x == ch)
            chcount++;
        // Current character is not ch
        else
            othercount++;
    }
 
    // Return the final result
    return (chcount - othercount);
}
 
// Function to calculate maximum number of string
// with one character as majority
int MaximumNumberOfString(string A[], int N)
{
    // Initializing ans with 0, to store final answer
    int ans = 0;
 
    // For every character from 'a' to 'z' run loop
    for (char ch = 'a'; ch <= 'z'; ch++) {
 
        // Initialize arr to store character count
        // difference
        vector arr(N);
 
        // Traverse every string
        for (int i = 0; i < N; i++) {
 
            // Calculate the required value by
            // function call and assign it to arr[i]
            arr[i] = CalDiff(A[i], ch);
        }
 
        // Sort arr[] in decreasing order
        sort(arr.begin(), arr.end(), greater());
 
        // Initialize temp and count as 0
        int temp = 0, count = 0;
 
        // Adding the first arr[] element to temp
        temp += arr[0];
 
        // Maintaining j as index
        int j = 1;
 
        // Run loop until temp <= 0
        while (temp > 0) {
            // Increasing count
            count++;
 
            // Adding temp with next arr[] element
            if (j != N)
                temp += arr[j++];
            else
                break;
        }
 
        // Set ans as max of ans and count
        ans = max(ans, count);
    }
 
    // Returning the final result
    return ans;
}
 
// Driver Code
int main()
{
    // Input
    string A[] = { "aba", "abcde", "aba" };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function call
    cout << MaximumNumberOfString(A, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG
{
 
// Function to calculate (occurrence of ch -
// occurrence of all other characters combined)
static int CalDiff(String s, char ch)
{
   
    // Initialize ch count as 0
    int chcount = 0;
 
    // Initialize all other char count as 0
    int othercount = 0;
 
    // Traversing the String
    for (int x : s.toCharArray())
    {
       
        // Current character is ch
        if (x == ch)
            chcount++;
       
        // Current character is not ch
        else
            othercount++;
    }
 
    // Return the final result
    return (chcount - othercount);
}
 
// Function to calculate maximum number of String
// with one character as majority
static int MaximumNumberOfString(String A[], int N)
{
   
    // Initializing ans with 0, to store final answer
    int ans = 0;
 
    // For every character from 'a' to 'z' run loop
    for (char ch = 'a'; ch <= 'z'; ch++) {
 
        // Initialize arr to store character count
        // difference
       int []arr = new int[N];
 
        // Traverse every String
        for (int i = 0; i < N; i++) {
 
            // Calculate the required value by
            // function call and assign it to arr[i]
            arr[i] = CalDiff(A[i], ch);
        }
 
        // Sort arr[] in decreasing order
        Arrays.sort(arr);
        arr = reverse(arr);
 
        // Initialize temp and count as 0
        int temp = 0, count = 0;
 
        // Adding the first arr[] element to temp
        temp += arr[0];
 
        // Maintaining j as index
        int j = 1;
 
        // Run loop until temp <= 0
        while (temp > 0)
        {
           
            // Increasing count
            count++;
 
            // Adding temp with next arr[] element
            if (j != N)
                temp += arr[j++];
            else
                break;
        }
 
        // Set ans as max of ans and count
        ans = Math.max(ans, count);
    }
 
    // Returning the final result
    return ans;
}
static int[] reverse(int a[]) {
    int i, n = a.length, t;
    for (i = 0; i < n / 2; i++) {
        t = a[i];
        a[i] = a[n - i - 1];
        a[n - i - 1] = t;
    }
    return a;
}
   
// Driver Code
public static void main(String[] args)
{
   
    // Input
    String A[] = { "aba", "abcde", "aba" };
    int N = A.length;
 
    // Function call
    System.out.print(MaximumNumberOfString(A, N));
 
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python 3 program for the above approach
 
# Function to calculate (occurrence of ch -
# occurrence of all other characters combined)
def CalDiff(s, ch):
    # Initialize ch count as 0
    chcount = 0
 
    # Initialize all other char count as 0
    othercount = 0
 
    # Traversing the string
    for x in s:
        # Current character is ch
        if (x == ch):
            chcount += 1
        # Current character is not ch
        else:
            othercount += 1
 
    # Return the final result
    return (chcount - othercount)
 
# Function to calculate maximum number of string
# with one character as majority
def MaximumNumberOfString(A, N):
    # Initializing ans with 0, to store final answer
    ans = 0
 
    # For every character from 'a' to 'z' run loop
    for ch in range(97,123,1):
        # Initialize arr to store character count
        # difference
        arr = [0 for i in range(N)]
 
        # Traverse every string
        for i in range(N):
            # Calculate the required value by
            # function call and assign it to arr[i]
            arr[i] = CalDiff(A[i], chr(ch))
 
        # Sort arr[] in decreasing order
        arr.sort(reverse = True)
 
        # Initialize temp and count as 0
        temp = 0
        count = 0
 
        # Adding the first arr[] element to temp
        temp += arr[0]
 
        # Maintaining j as index
        j = 1
 
        # Run loop until temp <= 0
        while (temp > 0):
            # Increasing count
            count += 1
 
            # Adding temp with next arr[] element
            if (j != N):
                temp += arr[j]
                j += 1
            else:
                break
 
        # Set ans as max of ans and count
        ans = max(ans, count)
 
    # Returning the final result
    return ans
 
# Driver Code
if __name__ == '__main__':
    # Input
    A = ["aba", "abcde", "aba"]
    N = len(A)
 
    # Function call
    print(MaximumNumberOfString(A, N))
     
    # This code is contributed by SURENDRA_GANGWAR.


Javascript


输出
2

时间复杂度: O(N * |s|),其中 |s|是最大字符串长度。
辅助空间: O(N)

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