Challenge: Letter Histogram
Completed
Read one word of lowercase letters. For each letter that appears, in a–z order, print the letter, a colon, a space and one * per time it appears. Use an int[26] array.
Input
One word (lowercase letters only).
Output
One line per letter used, like a: ***.
Example
Input
banana
Output
a: *** b: * n: **
Editor
Java
Hints
count[c - 'a']++ for every character.
Loop letter from 0 to 25 and turn it back with (char) ('a' + letter).
Solution explanation
Counting is O(n); printing walks the 26 counters. The array keeps the letters in order for free.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word = sc.next();
int[] count = new int[26];
for (int i = 0; i < word.length(); i++) count[word.charAt(i) - 'a']++;
StringBuilder sb = new StringBuilder();
for (int letter = 0; letter < 26; letter++) {
if (count[letter] == 0) continue;
sb.append((char) ('a' + letter)).append(": ");
for (int k = 0; k < count[letter]; k++) sb.append('*');
sb.append('\n');
}
System.out.print(sb);
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module