返回介绍

solution / 2200-2299 / 2278.Percentage of Letter in String / README_EN

发布于 2024-06-17 01:03:07 字数 2967 浏览 0 评论 0 收藏 0

2278. Percentage of Letter in String

中文文档

Description

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

 

Example 1:

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:

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.

Solutions

Solution 1

class Solution:
  def percentageLetter(self, s: str, letter: str) -> int:
    return s.count(letter) * 100 // len(s)
class Solution {
  public int percentageLetter(String s, char letter) {
    int cnt = 0;
    for (char c : s.toCharArray()) {
      if (c == letter) {
        ++cnt;
      }
    }
    return cnt * 100 / s.length();
  }
}
class Solution {
public:
  int percentageLetter(string s, char letter) {
    int cnt = 0;
    for (char& c : s) cnt += c == letter;
    return cnt * 100 / s.size();
  }
};
func percentageLetter(s string, letter byte) int {
  cnt := 0
  for i := range s {
    if s[i] == letter {
      cnt++
    }
  }
  return cnt * 100 / len(s)
}
function percentageLetter(s: string, letter: string): number {
  let count = 0;
  let total = s.length;
  for (let i of s) {
    if (i === letter) count++;
  }
  return Math.floor((count / total) * 100);
}
impl Solution {
  pub fn percentage_letter(s: String, letter: char) -> i32 {
    let mut count = 0;
    for c in s.chars() {
      if c == letter {
        count += 1;
      }
    }
    ((count * 100) / s.len()) as i32
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文