-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCharacterOccurrenceCounter.java
65 lines (50 loc) · 1.79 KB
/
CharacterOccurrenceCounter.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package string;
import java.util.HashMap;
import java.util.Map;
public class CharacterOccurrenceCounter {
/**
* Main method of the class for the following question:
* Find the counts the occurrences of each character in a given input string.
* */
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
String input = scanner.nextLine();
// Optimized Method:
countCharacterOccurrences(input);
System.out.println();
// Brute Force Method:
occurringChar(input);
}
// Brute Force Method:
private static void occurringChar(String input) {
int[] count = new int[256]; // ASCII_SIZE
for (int i = 0; i < input.length(); i++)
count[input.charAt(i)]++;
char[] ch = new char[input.length()];
for (int i = 0; i < input.length(); i++) {
ch[i] = input.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (input.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println(input.charAt(i) + " : " + count[input.charAt(i)]);
}
}
// Optimized Method:
private static void countCharacterOccurrences(String input) {
Map<Character, Integer> countMap = new HashMap<>();
for (char ch : input.toCharArray()) {
if (countMap.containsKey(ch)) {
countMap.put(ch, countMap.get(ch) + 1);
} else {
countMap.put(ch, 1);
}
}
for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}