-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfreqS.java
More file actions
50 lines (40 loc) · 1.17 KB
/
freqS.java
File metadata and controls
50 lines (40 loc) · 1.17 KB
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
// Java implementation to print the character and
// its frequency in order of its occurrence
public class freqS {
static final int SIZE = 26;
// function to print the character and its
// frequency in order of its occurrence
static void printCharWithFreq(String str)
{
// size of the string 'str'
int n = str.length();
// 'freq[]' implemented as hash table
int[] freq = new int[SIZE];
// accumulate frequency of each character
// in 'str'
for (int i = 0; i < n; i++)
freq[str.charAt(i) - 'a']++;
// traverse 'str' from left to right
for (int i = 0; i < n; i++) {
// if frequency of character str.charAt(i)
// is not equal to 0
if (freq[str.charAt(i) - 'a'] != 0) {
// print the character along with its
// frequency
System.out.print(str.charAt(i));
System.out.print(freq[str.charAt(i) - 'a'] + " ");
// update frequency of str.charAt(i) to
// 0 so that the same character is not
// printed again
freq[str.charAt(i) - 'a'] = 0;
}
}
}
// Driver program to test above
public static void main(String args[])
{
String str = "geeksforgeeks";
printCharWithFreq(str);
}
}
// This code is contributed by Sumit Ghosh