给定字符串str ,任务是根据每个字符的频率以升序对字符串进行排序。如果两个元素具有相同的频率,则将它们按字典顺序排序。
例子:
Input: str = “geeksforgeeks”
Output: forggkksseeee
Explanation:
Frequency of characters: g2 e4 k2 s2 f1 o1 r1
Sorted characters according to frequency: f1 o1 r1 g2 k2 s2 e4
f, o, r occurs one time so they are ordered lexicographically and so are g, k and s.
Hence the final output is forggkksseeee.
Input: str = “abc”
Output: abc
方法的想法是将每个字符及其频率存储在成对的向量中,然后根据存储的频率对向量对进行排序。最后,按顺序打印矢量。
下面是上述方法的实现:
C++
// C++ implementation to Sort strings
// according to the frequency of
// characters in ascending order
#include
using namespace std;
// Returns count of character in the string
int countFrequency(string str, char ch)
{
int count = 0;
for (int i = 0; i < str.length(); i++)
// Check for vowel
if (str[i] == ch)
++count;
return count;
}
// Function to sort the string
// according to the frequency
void sortArr(string str)
{
int n = str.length();
// Vector to store the frequency of
// characters with respective character
vector > vp;
// Inserting frequency
// with respective character
// in the vector pair
for (int i = 0; i < n; i++) {
vp.push_back(
make_pair(
countFrequency(str, str[i]),
str[i]));
}
// Sort the vector, this will sort the pair
// according to the number of characters
sort(vp.begin(), vp.end());
// Print the sorted vector content
for (int i = 0; i < vp.size(); i++)
cout << vp[i].second;
}
// Driver code
int main()
{
string str = "geeksforgeeks";
sortArr(str);
return 0;
}
Python3
# Python3 implementation to Sort strings
# according to the frequency of
# characters in ascending order
# Returns count of character in the string
def countFrequency(string , ch) :
count = 0;
for i in range(len(string)) :
# Check for vowel
if (string[i] == ch) :
count += 1;
return count;
# Function to sort the string
# according to the frequency
def sortArr(string) :
n = len(string);
# Vector to store the frequency of
# characters with respective character
vp = [];
# Inserting frequency
# with respective character
# in the vector pair
for i in range(n) :
vp.append((countFrequency(string, string[i]), string[i]));
# Sort the vector, this will sort the pair
# according to the number of characters
vp.sort();
# Print the sorted vector content
for i in range(len(vp)) :
print(vp[i][1],end="");
# Driver code
if __name__ == "__main__" :
string = "geeksforgeeks";
sortArr(string);
# This code is contributed by Yash_R
输出:
forggkksseeee
时间复杂度: O(n * log(n))
辅助空间: O(n)