2278. Percentage of Letter in String
Description
Given a string s
and a character letter
, return the percentage of characters in s
that equal letter
rounded down to the nearest whole percent.
Example 1:
Input: s = "foobar", letter = "o" Output: 33 Explanation: The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.
Example 2:
Input: s = "jjjj", letter = "k" Output: 0 Explanation: The percentage of characters in s that equal the letter 'k' is 0%, so we return 0.
Constraints:
1 <= s.length <= 100
s
consists of lowercase English letters.letter
is a lowercase English letter.
Solutions
Solution 1: Counting
We can traverse the string $\textit{s}$ and count the number of characters that are equal to $\textit{letter}$. Then, we calculate the percentage using the formula $\textit{count} \times 100 , / , \textit{len}(\textit{s})$.
Time complexity is $O(n)$, where $n$ is the length of the string $\textit{s}$. Space complexity is $O(1)$.
Python3
class Solution:
def percentageLetter(self, s: str, letter: str) -> int:
return s.count(letter) * 100 // len(s)
Java
class Solution {
public int percentageLetter(String s, char letter) {
int cnt = 0;
for (char c : s.toCharArray()) {
if (c == letter) {
++cnt;
}
}
return cnt * 100 / s.length();
}
}
C++
class Solution {
public:
int percentageLetter(string s, char letter) {
return 100 * ranges::count(s, letter) / s.size();
}
};
Go
func percentageLetter(s string, letter byte) int {
return strings.Count(s, string(letter)) * 100 / len(s)
}
TypeScript
function percentageLetter(s: string, letter: string): number {
const count = s.split('').filter(c => c === letter).length;
return Math.floor((100 * count) / s.length);
}
Rust
impl Solution {
pub fn percentage_letter(s: String, letter: char) -> i32 {
let count = s.chars().filter(|&c| c == letter).count();
(100 * count as i32 / s.len() as i32) as i32
}
}