Skip to content

Latest commit

 

History

History
119 lines (90 loc) · 3.32 KB

2278.md

File metadata and controls

119 lines (90 loc) · 3.32 KB
title description keywords
2278. 字母在字符串中的百分比
LeetCode 2278. 字母在字符串中的百分比题解,Percentage of Letter in String,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。
LeetCode
2278. 字母在字符串中的百分比
字母在字符串中的百分比
Percentage of Letter in String
解题思路
字符串

2278. 字母在字符串中的百分比

🟢 Easy  🔖  字符串  🔗 力扣 LeetCode

题目

Given a string s and a character letter, return _the percentage of characters in _s that equalletter 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.

题目大意

给你一个字符串 s 和一个字符 letter ,返回在 s 中等于 letter 字符所占的 百分比 ,向下取整到最接近的百分比。

示例 1:

输入: s = "foobar", letter = "o"

输出: 33

解释:

等于字母 'o' 的字符在 s 中占到的百分比是 2 / 6 * 100% = 33% ,向下取整,所以返回 33 。

示例 2:

输入: s = "jjjj", letter = "k"

输出: 0

解释:

等于字母 'k' 的字符在 s 中占到的百分比是 0% ,所以返回 0 。

提示:

  • 1 <= s.length <= 100
  • s 由小写英文字母组成
  • letter 是一个小写英文字母

解题思路

  1. 统计字符出现次数

    • 遍历字符串 s,统计字符 letter 出现的次数 count
  2. 计算百分比

    • 使用公式 percentage = floor(count * 100 / s.length)
    • 向下取整可以直接使用 Math.floor()

复杂度分析

  • 时间复杂度O(n),其中 n 是字符串长度,遍历字符串一次。
  • 空间复杂度O(1),使用了常量空间。

代码

/**
 * @param {string} s
 * @param {character} letter
 * @return {number}
 */
var percentageLetter = function (s, letter) {
	const n = s.length; // 字符串的总长度
	let count = 0; // 统计 letter 出现的次数
	for (let char of s) {
		if (char === letter) {
			count++;
		}
	}
	// 计算百分比并向下取整
	return Math.floor((count * 100) / n);
};

相关题目

题号 标题 题解 标签 难度 力扣
451 根据字符出现频率排序 [✓] 哈希表 字符串 桶排序 3+ 🟠 🀄️ 🔗