-
Notifications
You must be signed in to change notification settings - Fork 19
/
Frequency of each Character in Array .cpp
92 lines (74 loc) · 1.83 KB
/
Frequency of each Character in Array .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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Method -1 (Basic)
#include <bits/stdc++.h>
using namespace std;
#define SIZE 26
// function to print the character and its frequency
// in order of its occurrence
void printCharWithFreq(string str)
{
// size of the string 'str'
int n = str.size();
// 'freq[]' implemented as hash table
int freq[SIZE];
// initialize all elements of freq[] to 0
memset(freq, 0, sizeof(freq));
// accumulate freqeuncy of each character in 'str'
for (int i = 0; i < n; i++)
freq[str[i] - 'a']++;
// traverse 'str' from left to right
for (int i = 0; i < n; i++) {
// if frequency of character str[i] is not
// equal to 0
if (freq[str[i] - 'a'] != 0) {
// print the character along with its
// frequency
cout << str[i] << freq[str[i] - 'a'] << " ";
// update frequency of str[i] to 0 so
// that the same character is not printed
// again
freq[str[i] - 'a'] = 0;
}
}
}
int main()
{
string str ;
getline(cin,str);
printCharWithFreq(str);
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Method -2 (Efficient -Using Hashing)
#include <bits/stdc++.h>
using namespace std;
void prCharWithFreq(string s)
{
// Store all characters and
// their frequencies in dictionary
unordered_map<char, int> d;
for(char i : s)
{
d[i]++;
}
// Print characters and their
// frequencies in same order
// of their appearance
for(char i : s)
{
// Print only if this
// character is not printed
// before
if(d[i] != 0)
{
cout << i << d[i] << " ";
d[i] = 0;
}
}
}
// Driver Code
int main()
{
string str ;
getline(cin,str);
prCharWithFreq(s);
}