About implementing character counting (with.Java)
In this article, we looked at implementing character counting (with.Java).
Weβll be solving a coding test problem, reflecting on the problem we solved, and learning about other ways to solve it.
Letβs start with the problem
Problem
Given a string my_string that contains only alphabetical characters.
count of βAβ in my_string, count of βBβ in my_string,β¦, count of βZβ in my_string, count of βaβ in my_string, count of βbβ in my_string,β¦
Write a solution function that returns an array of integers of length 52 containing the number of occurrences of βzβ in my_string in order.
Example input and output
my_string: βProgrammersβ
result: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0]
In my_string, there is one βPβ, one βaβ, one βeβ, one βgβ, two βmβ, one βoβ, three βrβ, and one βsβ, so.
returns [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0].
My solution to the problem
class Solution {
public int[] solution(String my_string) {
int[] answer = new int[52];
for (int i = 0; i < my_string.length(); i++) {
char c = my_string.charAt(i);
if (c >= 'A' && c <= 'Z') {
answer[c - 'A']++;
} else if (c >= 'a' && c <= 'z') {
answer[26 + c - 'a']++;
}
}
return answer;
}
}
Solution
This code counts the frequency of occurrence of alphabetical characters within the given string my_string.
The result is returned as an array of int[], where each element of the array represents the number of occurrences of a particular alphabetical character.
The answer array is an integer array of length 52, storing counts for the uppercase and lowercase letters of the alphabet, respectively.
Indexes 0 through 25 store the number of occurrences of the uppercase letters βAβ through βZβ.
Indexes 26 through 51 store the number of occurrences of lowercase letters βAβ through βZβ.
Hereβs how the code works:
Iterate over the length of my_string, checking for each letter c.
If c is an uppercase letter, subtract βAβ to find the position of that uppercase letter, and increment the count at that position. (answer[c - βAβ]++)
If c is a lowercase letter, subtract βaβ and add 26 to find the corresponding lowercase letter and increment the count at that position. (answer[26 + c - βaβ]++)
When it has finished processing all the characters, it returns an array of answer. This array represents the number of occurrences of each letter of the alphabet in the string.