LeetCode 题解工作台

字母在字符串中的百分比

给你一个字符串 s 和一个字符 letter ,返回在 s 中等于 letter 字符所占的 百分比 ,向下取整到最接近的百分比。 示例 1: 输入: s = "foobar", letter = "o" 输出: 33 解释: 等于字母 'o' 的字符在 s 中占到的百分比是 2 / 6 * 100…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们可以遍历字符串 ,统计其中等于 的字符的个数,然后根据公式 $\textit{count} \times 100 \, / \, \textit{len}(\textit{s})$ 计算百分比。 时间复杂度 ,其中 为字符串 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 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 是一个小写英文字母
lightbulb

解题思路

方法一:计数

我们可以遍历字符串 s\textit{s},统计其中等于 letter\textit{letter} 的字符的个数,然后根据公式 count×100/len(s)\textit{count} \times 100 \, / \, \textit{len}(\textit{s}) 计算百分比。

时间复杂度 O(n)O(n),其中 nn 为字符串 s\textit{s} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def percentageLetter(self, s: str, letter: str) -> int:
        return s.count(letter) * 100 // len(s)
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

字母在字符串中的百分比题解:String-driven solution … | LeetCode #2278 简单