Every char has a number
Inside the computer, each character is a number: 'a' is 97, 'b' is 98, and so on up to 'z' = 122. So c - 'a' turns a lowercase letter into 0 … 25 – a perfect array index!
public class Main {
public static void main(String[] args) {
char c = 'd';
System.out.println((int) c); // its number
System.out.println(c - 'a'); // position in the alphabet, from 0
System.out.println((char) ('a' + 4)); // and back again
System.out.println('7' - '0'); // a digit char to its value
}
}Output
100 3 e 7
Counting letters
Make 26 counters, one per letter. Walk through the word once and add 1 to the right counter:
public class Main {
public static void main(String[] args) {
String word = "banana";
int[] count = new int[26];
for (int i = 0; i < word.length(); i++) {
count[word.charAt(i) - 'a']++;
}
for (int letter = 0; letter < 26; letter++) {
if (count[letter] > 0) {
System.out.println((char) ('a' + letter) + ": " + count[letter]);
}
}
}
}Output
a: 3 b: 1 n: 2
This is O(n) for a word of length n, and the output is already in a–z order.
Anagrams in one line of thinking
Two words are anagrams (like listen and silent) if they use exactly the same letters. Count up for the first word, count down for the second – if every counter ends at 0, they match:
public class Main {
static boolean anagrams(String a, String b) {
if (a.length() != b.length()) return false;
int[] count = new int[26];
for (int i = 0; i < a.length(); i++) {
count[a.charAt(i) - 'a']++;
count[b.charAt(i) - 'a']--;
}
for (int x : count) if (x != 0) return false;
return true;
}
public static void main(String[] args) {
System.out.println(anagrams("listen", "silent"));
System.out.println(anagrams("apple", "paper"));
}
}Output
true false
Tip:
Character.isLetter(c),Character.isDigit(c),Character.toLowerCase(c)andCharacter.toUpperCase(c)save you from remembering the numbers.