给定一个字符串str和一个整数K ,任务是找到字符串第K个最频繁出现的字符。如果有多个字符可以解释为第K个最常见的字符,则打印其中的任何一个。
例子:
Input: str = “GeeksforGeeks”, K = 3
Output: f
Explanation:
K = 3, here ‘e’ appears 4 times
& ‘g’, ‘k’, ‘s’ appears 2 times
& ‘o’, ‘f’, ‘r’ appears 1 time.
Any output from ‘o’ (or) ‘f’ (or) ‘r’ will be correct.
Input: str = “trichotillomania”, K = 2
Output: l
方法
- 这个想法是在Hashmap中使用字符作为键并将它们的出现存储在字符串。
- 排序Hashmap并找到第K个字符。
下面是上述方法的实现。
C++
// C++ program to find kth most frequent
// character in a string
#include
using namespace std;
// Used for sorting by frequency.
bool sortByVal(const pair& a,
const pair& b)
{
return a.second > b.second;
}
// function to sort elements by frequency
char sortByFreq(string str, int k)
{
// Store frequencies of characters
unordered_map m;
for (int i = 0; i < str.length(); ++i)
m[str[i]]++;
// Copy map to vector
vector > v;
copy(m.begin(), m.end(), back_inserter(v));
// Sort the element of array by frequency
sort(v.begin(), v.end(), sortByVal);
// Find k-th most frequent item. Please note
// that we need to consider only distinct
int count = 0;
for (int i = 0; i < v.size(); i++) {
// Increment count only if frequency is
// not same as previous
if (i == 0 || v[i].second != v[i - 1].second)
count++;
if (count == k)
return v[i].first;
}
return -1;
}
// Driver program
int main()
{
string str = "geeksforgeeks";
int k = 3;
cout << sortByFreq(str, k);
return 0;
}
输出:
r
时间复杂度: O(NlogN)请注意,这是时间复杂度的上限。如果我们认为字母大小为常数(例如小写英文字母大小为26),则可以说时间复杂度为O(N)。矢量大小永远不会超过字母大小。
辅助空间: O(N)