Ещё одна простая задачка — определение процентного содержания целевого символа в исходной строке. Пара решений:
- через стримы (примитивно, без кастомной свёртки, да и помедленней)
- и через цикл
for
.
Стримы
public int percentageLetter(String s, char letter) {
long cnt = s.chars().filter(it -> it == (int) letter).count();
return (int) (100 * cnt / s.length());
}
Success: Runtime:2 ms, faster than 12.22% of Java online submissions. Memory Usage:40.6 MB, less than 45.95% of Java online submissions.
Цикл
public int percentageLetter(String s, char letter) {
int cnt = 0;
for (char c : s.toCharArray()) {
cnt += c == letter ? 1 : 0;
}
return 100 * cnt / s.length();
}
Success: Runtime:0 ms, faster than 100.00% of Java online submissions. Memory Usage:40.1 MB, less than 88.72% of Java online submissions.
Решение на гитхабе.
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.
https://leetcode.com/problems/percentage-of-letter-in-string/