要选择的字符串的最大数量,以便有一个多数字符。
- 最后更新 : 2021年8月10日
给定一个由N个 小写字母组成的数组 A[],任务是找到最大数量的字符串,使一个字符占多数,即一个字符在所有字符串中的出现率大于其他所有字符的总和。
例子。
输入。 A[] = {"aba", "abcde", "aba"}
输出。 2
解释。 在选择{"aba", "aba"}时,字符'a'的出现次数为4,其余字符的出现次数为2,小于4。 因此,最多可以选择2个字符串。输入。 A[] = {"bzc", "zzdz", "e"}
输出。 3
解释。 所有的字符串都可以被选择,其中'z'占多数。
办法。对 这个问题有一个贪婪的解决方案。其思路是:考虑从**'a'到'z'的所有小写字母,对于每个字符,找出可以选择的最大数量的字符串,使该字符的出现率大于其他所有字符的总和。其中的最大值将是答案。现在的主要问题是如何找到最大数量的字符串,使一个特定的字符占多数,为了解决这个问题,使用贪婪算法。我们的想法是,要找到一个特定字符"ch "的最大数量的字符串,尽量选择"ch "的出现与所有其他字符的出现相比最大的字符串,即("ch "的出现-所有其他字符的出现)** 最大的 字符串,这样就有可能在未来增加更多的字符串。
按照下面的步骤来解决这个问题。
- 定义一个函数 **CalDif(string s, char ch)**并执行以下任务。
- 将变量chcount初始化为0,以存储该字符的计数,othercount初始化为0,以存储其他字符的计数。
- 使用变量x遍历字符串 s并执行以下任务。
- 如果当前位置的字符是ch,那么将chcount的值增加1,否则将othercount的值增加1。
- 返回chcount和othercount之间的差值**。**
- 初始化变量ans 并赋值0,它将存储最终的答案。
- 使用变量i遍历小写字母范围 [a, z],并执行以下步骤。
- 执行完上述步骤后,打印ans的值作为答案。
下面是上述方法的实现。
C++
// C++ program for the above approach#include <bits/stdc++.h>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 0int chcount = 0;// Initialize all other char count as 0int othercount = 0;// Traversing the stringfor (auto x : s) {// Current character is chif (x == ch)chcount++;// Current character is not chelseothercount++;}// Return the final resultreturn (chcount - othercount);}// Function to calculate maximum number of string// with one character as majorityint MaximumNumberOfString(string A[],int N){// Initializing ans with 0, to store final answerint ans = 0;// For every character from 'a' to 'z' run loopfor (char ch ='a'; ch <='z'; ch++) {// Initialize arr to store character count// differencevector<int> arr(N);// Traverse every stringfor (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 ordersort(arr.begin(), arr.end(), greater<int>());// Initialize temp and count as 0int temp = 0, count = 0;// Adding the first arr[] element to temptemp += arr[0];// Maintaining j as indexint j = 1;// Run loop until temp <= 0while (temp > 0) {// Increasing countcount++;// Adding temp with next arr[] elementif (j != N)temp += arr[j++];elsebreak;}// Set ans as max of ans and countans = max(ans, count);}// Returning the final resultreturn ans;}// Driver Codeint main(){// Inputstring A[] = {"aba","abcde","aba" };int N =sizeof(A) /sizeof(A[0]);// Function callcout << MaximumNumberOfString(A, N);return 0;} |
输出
2
**时间复杂度。**O(N * |s|),其中|s|是最大字符串长度。
辅助空间。O(N)
读者请注意!现在不要停止学习。掌握所有重要的DSA概念。 DSA自学课程以适合学生的价格掌握所有重要的DSA概念,并为行业做好准备。 要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.
如果你想参加专家的现场课程 ,请参考 面向在职人士的DSA现场课程 和 面向学生的竞争性编程直播.
我的个人笔记 arrow_drop_up
保存