Leetcode 2278. Percentage of Letter in String
You are given a string s
and a character letter
. Your task is to return the percentage of characters in s
that equal letter
rounded down to the nearest whole percent.
The formula to calculate the percentage is:
[ \text{percentage} = \left(\frac{\text{number of occurrences of letter
}}{\text{length of s
}}\right) \times 100 ]
What is the length range of the string s ? (Typically, constraints might be 1 <= |
s | <= 100) |
s
always non-empty?s
contain non-alphabetic characters?s
to count the occurrences of letter
.s
. This is because we need to iterate through the string once to count the occurrences of letter
.public class Solution {
public int percentageLetter(String s, char letter) {
int count = 0;
int length = s.length();
// Count the occurrences of `letter` in the string
for (int i = 0; i < length; i++) {
if (s.charAt(i) == letter) {
count++;
}
}
// Calculate the percentage and round down using integer division
int percentage = (count * 100) / length;
return percentage;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test cases
System.out.println(solution.percentageLetter("foobar", 'o')); // Expected output: 33
System.out.println(solution.percentageLetter("jjjj", 'j')); // Expected output: 100
System.out.println(solution.percentageLetter("abcde", 'f')); // Expected output: 0
}
}
count
to zero.s
and increment count
whenever we find the character letter
.This way, we can effectively compute the percentage of occurrences of a given character in a string, rounded down to the nearest whole percentage.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?