-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOccuringCharacters.java
48 lines (41 loc) · 1.83 KB
/
OccuringCharacters.java
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
// Write a Java program to find the maximum occurring character in a string.
public class OccuringCharacters {
public static void main(String[] args) {
String str = "grass is greener on the other side";
System.out.println("The string is: " + str);
int[] freq = new int[str.length()];
char minChar = str.charAt(0), maxChar = str.charAt(0);
int i, j, min, max;
//Converts given string into character array
char string[] = str.toCharArray();
//Count each word in given string and store in array freq
for(i = 0; i < string.length; i++) {
freq[i] = 1;
for(j = i+1; j < string.length; j++) {
if(string[i] == string[j] && string[i] != ' ' && string[i] != '0') {
freq[i]++;
//Set string[j] to 0 to avoid printing visited character
string[j] = '0';
}
}
}
//Determine minimum and maximum occurring characters
min = max = freq[0];
for(i = 0; i <freq.length; i++) {
//If min is greater than frequency of a character
//then, store frequency in min and corresponding character in minChar
if(min > freq[i] && freq[i] != '0') {
min = freq[i];
minChar = string[i];
}
//If max is less than frequency of a character
//then, store frequency in max and corresponding character in maxChar
if(max < freq[i]) {
max = freq[i];
maxChar = string[i];
}
}
System.out.println("Minimum occurring character: " + minChar);
System.out.println("Maximum occurring character: " + maxChar);
}
}