Character Frequency
Problem
Read one line. Count every letter (a to z, upper and lower case are the same). Print one line for each letter that appears, in alphabetical order, in the form letter count. Ignore all other characters.
Constraints
- 1 <= length <= 10^5, ASCII text
Examples
Input
Hello
Output
e 1 h 1 l 2 o 1
Solutions
A fixed table with 26 places is the fastest counter for letters. The index of a letter is its distance from a.
/*
* Problem : Process one line of text.
* Input : One line of text.
* Output : One line per letter.
* Approach: Use a counter table.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String s) {
// Step 1: A table of 26 counters, one for each letter.
int[] counts = new int[26];
// Step 2: Look at every character. Count it if it is a letter.
for (char c : s.toLowerCase().toCharArray()) {
if (c >= 'a' && c <= 'z') {
counts[c - 'a']++;
}
}
// Step 3: Make one line for each letter that has a count above 0.
java.util.List<String> lines = new java.util.ArrayList<>();
for (int i = 0; i < 26; i++) {
if (counts[i] > 0) {
lines.add((char) ('a' + i) + " " + counts[i]);
}
}
return lines.toArray(new String[0]);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(String.join("\n", solve(s)));
}
}
Hints (1)
- Which index belongs to the letter c?