-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathsort_characters_by_their_occurrence.cpp
70 lines (59 loc) · 1.71 KB
/
sort_characters_by_their_occurrence.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
Given a string,
sort it in decreasing order based on the occurrence of each characters.
then return new string.
*/
#include <bits/stdc++.h>
using namespace std;
// this get_string_sort_characters_by_their_occurrence will give us the new string
string get_string_sort_characters_by_their_occurrence(string s)
{
// we will insert characters into the map
map < char, int > occur_char;
for(int i = 0; i < (int)s.size(); i++)
{
occur_char[s[i]]++;
}
/* multimap can contain duplicate keys. that's why we will use it.
here multimap's key is the occurrence of each character
and multimap's value is that particular character.
greater < int > will store them in descending order.
*/
multimap < int , char, greater < int > > occur_char_2;
for(auto i : occur_char)
{
occur_char_2.insert( { i.second , i.first } );
}
string new_string = "";
for(auto i : occur_char_2)
{
int freq = i.first;
while(freq--)
{
/* for each occurrence
we will add particular character to
our new string
*/
new_string += i.second;
}
}
return new_string;
}
int main()
{
cout << "Enter the string : ";
string s;
cin >> s;
string new_string = get_string_sort_characters_by_their_occurrence(s);
cout << "The New String based on the occurrence of each characters is : \n";
cout << new_string << endl;
}
/*
Standard Input and Output
Enter the string :
GMAFGGGMMAF
The New String based on the occurrence of each characters is :
GGGGMMMAAFF
Time Complexity : O( log N )
Space Complexity : O( N )
*/