Leetcode 2278. Percentage of Letter in String
Given a string s
and a character letter
, return the percentage of characters in the string s
that equal letter
rounded down to the nearest integer.
What is the length of the string s ? (Typically, for LeetCode problems, inputs can vary, but a common constraint could be ( 1 \leq |
s | \leq 1000 )). |
Is the string s
guaranteed to contain only lowercase/uppercase alphabetic characters, or can there be other characters?
#include <string>
#include <cmath>
int percentageLetter(std::string s, char letter) {
int count = 0;
int length = s.length();
for (char c : s) {
if (c == letter) {
count++;
}
}
// Calculate the percentage and round down
int percentage = (count * 100) / length;
return percentage;
}
count
to keep track of how many times letter
appears in the string s
.length = s.length()
.letter
, increment the count.(count * 100) / length
.n
is the length of the string s
.This approach ensures that the function runs efficiently even for the upper limits of string length.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?