2278. Percentage of Letter in String
Explanation:
To solve this problem, we need to iterate through the given string s
and count the number of occurrences of the character letter
. Then we calculate the percentage of occurrences of letter
in s
and round it down to the nearest whole percentage.
- Initialize a variable
count
to store the number of occurrences ofletter
. - Iterate through each character in the string
s
:- If the character is equal to
letter
, increment thecount
.
- If the character is equal to
- Calculate the percentage of occurrences of
letter
ins
by dividingcount
by the length ofs
and multiplying by 100. - Return the rounded down value of the percentage.
:
class Solution {
public int percentageOfLetterInString(String s, char letter) {
int count = 0;
for (char c : s.toCharArray()) {
if (c == letter) {
count++;
}
}
return count * 100 / s.length();
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.