2278. Percentage of Letter in String

Question

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.*

Solution

一次遍历,计算字符出现的次数。
返回字符出现的次数除以字符长度乘以100。

Code

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int percentageLetter(String s, char letter) {
int count = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == letter){
count++;
}
}
return count * 100 / s.length();
}
}
Author

Xander

Posted on

2022-05-22

Updated on

2022-05-21

Licensed under

Comments