Problem#
Given a string s
and a character letter
, return _thepercentage of characters in _s
that equalletter
rounded down to the nearest whole percent.
Examples#
Example 1#
1
2
3
4
|
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#
1
2
3
4
|
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.
Solution#
Intuition#
Count the number of times letter
appears in s
, compute the percentage, and round down to the nearest integer.
Approach#
Use a simple loop or built-in count to count occurrences, then use integer division to get the floored percentage.
Code#
C++#
1
2
3
4
5
6
7
8
9
10
|
#include <string>
using namespace std;
class Solution {
public:
int percentageLetter(string s, char letter) {
int cnt = 0, n = s.size();
for (char c : s) if (c == letter) cnt++;
return cnt * 100 / n;
}
};
|
1
2
3
4
5
6
7
|
func percentageLetter(s string, letter byte) int {
cnt := 0
for i := 0; i < len(s); i++ {
if s[i] == letter { cnt++ }
}
return cnt * 100 / len(s)
}
|
Java#
1
2
3
4
5
6
7
|
class Solution {
public int percentageLetter(String s, char letter) {
int cnt = 0, n = s.length();
for (char c : s.toCharArray()) if (c == letter) cnt++;
return cnt * 100 / n;
}
}
|
Kotlin#
1
2
3
4
5
6
|
class Solution {
fun percentageLetter(s: String, letter: Char): Int {
val cnt = s.count { it == letter }
return cnt * 100 / s.length
}
}
|
Python#
1
2
|
def percentageLetter(s: str, letter: str) -> int:
return s.count(letter) * 100 // len(s)
|
Rust#
1
2
3
4
|
fn percentage_letter(s: &str, letter: char) -> i32 {
let cnt = s.chars().filter(|&c| c == letter).count();
(cnt * 100 / s.len()) as i32
}
|
TypeScript#
1
2
3
4
5
|
function percentageLetter(s: string, letter: string): number {
let cnt = 0;
for (const c of s) if (c === letter) cnt++;
return Math.floor(cnt * 100 / s.length);
}
|
Complexity#
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)