Percentage of Letter in String
The problem is asking for the percentage of a specific letter in a given string, and the result must be rounded down to the nearest whole percent. We can accomplish this by calculating the ratio of the occurrences of the given letter to the total length of the string, and then multiplying by 100.
Approach
- Count Occurrences: Count the occurrences of the given letter in the string.
- Calculate Percentage: Calculate the percentage as
(occurrences / length of the string) * 100
. - Round Down: Use the integer division
//
to round down to the nearest whole number.
Code Implementation
|
|
Example
- For
s = "foobar"
andletter = "o"
, the occurrences of “o” are 2, so the percentage is(2 / 6) * 100 = 33
and we return33
. - For
s = "jjjj"
andletter = "k"
, the occurrences of “k” are 0, so the percentage is0
and we return0
.
Complexity
The time complexity of this solution is O(n)
, where n
is the length of the string. This is because the count
method iterates through the string to count occurrences of the specified letter. The space complexity is O(1)
, since we only use a constant amount of extra space.