LeetCode 题解工作台
字母在字符串中的百分比
给你一个字符串 s 和一个字符 letter ,返回在 s 中等于 letter 字符所占的 百分比 ,向下取整到最接近的百分比。 示例 1: 输入: s = "foobar", letter = "o" 输出: 33 解释: 等于字母 'o' 的字符在 s 中占到的百分比是 2 / 6 * 100…
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们可以遍历字符串 ,统计其中等于 的字符的个数,然后根据公式 $\textit{count} \times 100 \, / \, \textit{len}(\textit{s})$ 计算百分比。 时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个字符串 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 <= 100s由小写英文字母组成letter是一个小写英文字母
解题思路
方法一:计数
我们可以遍历字符串 ,统计其中等于 的字符的个数,然后根据公式 计算百分比。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
class Solution:
def percentageLetter(self, s: str, letter: str) -> int:
return s.count(letter) * 100 // len(s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) where n is the length of s because each character is inspected once. Space complexity is O(1) since only counters are used, independent of input size. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can you count how many times the letter appears in s efficiently?
- question_mark
Do you handle rounding down correctly for percentages less than 1?
- question_mark
How do you handle the case when the letter does not appear at all?
常见陷阱
外企场景- error
Forgetting to round down and returning a float or rounded value incorrectly.
- error
Miscounting letter occurrences in strings with repeated characters.
- error
Not handling empty or single-character strings according to constraints.
进阶变体
外企场景- arrow_right_alt
Return the percentage as a floating-point number instead of rounding down.
- arrow_right_alt
Compute the percentage of multiple letters at once in the same string.
- arrow_right_alt
Handle uppercase letters and case-insensitive matching.