LeetCode 题解工作台

找到频率最高的元音和辅音

给你一个由小写英文字母( 'a' 到 'z' )组成的字符串 s 。你的任务是找出出现频率 最高 的元音( 'a' 、 'e' 、 'i' 、 'o' 、 'u' 中的一个)和出现频率 最高 的辅音(除元音以外的所有字母),并返回这两个频数之和。 注意 :如果有多个元音或辅音具有相同的最高频率,可以…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

我们先用一个哈希表或者一个长度为 的数组 统计每个字母的出现频率。然后我们遍历这个表,找出元音和辅音中出现频率最高的字母,返回它们的频率之和。 我们可以用一个变量 记录元音的最大频率,另一个变量 记录辅音的最大频率。遍历时,如果当前字母是元音,就更新 ;否则就更新 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由小写英文字母('a''z')组成的字符串 s。你的任务是找出出现频率 最高 的元音('a''e''i''o''u' 中的一个)和出现频率最高的辅音(除元音以外的所有字母),并返回这两个频数之和。

注意:如果有多个元音或辅音具有相同的最高频率,可以任选其中一个。如果字符串中没有元音或没有辅音,则其频率视为 0。

一个字母 x 的 频率 是它在字符串中出现的次数。

 

示例 1:

输入: s = "successes"

输出: 6

解释:

  • 元音有:'u' 出现 1 次,'e' 出现 2 次。最大元音频率 = 2。
  • 辅音有:'s' 出现 4 次,'c' 出现 2 次。最大辅音频率 = 4。
  • 输出为 2 + 4 = 6

示例 2:

输入: s = "aeiaeia"

输出: 3

解释:

  • 元音有:'a' 出现 3 次,'e' 出现 2 次,'i' 出现 2 次。最大元音频率 = 3。
  • s 中没有辅音。因此,最大辅音频率 = 0。
  • 输出为 3 + 0 = 3

 

提示:

  • 1 <= s.length <= 100
  • s 只包含小写英文字母
lightbulb

解题思路

方法一:计数

我们先用一个哈希表或者一个长度为 2626 的数组 cnt\textit{cnt} 统计每个字母的出现频率。然后我们遍历这个表,找出元音和辅音中出现频率最高的字母,返回它们的频率之和。

我们可以用一个变量 a\textit{a} 记录元音的最大频率,另一个变量 b\textit{b} 记录辅音的最大频率。遍历时,如果当前字母是元音,就更新 a\textit{a};否则就更新 b\textit{b}

最后返回 a+b\textit{a} + \textit{b} 即可。

时间复杂度 O(n)O(n),其中 nn 是字符串的长度。空间复杂度 (Σ)(|\Sigma|),其中 Σ|\Sigma| 是字母表的大小,这里是 2626

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def maxFreqSum(self, s: str) -> int:
        cnt = Counter(s)
        a = b = 0
        for c, v in cnt.items():
            if c in "aeiou":
                a = max(a, v)
            else:
                b = max(b, v)
        return a + b
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate uses a hashmap to efficiently track letter frequencies.

  • question_mark

    They properly handle both vowels and consonants in the same iteration.

  • question_mark

    The solution returns the sum of the frequencies of the most frequent vowel and consonant.

warning

常见陷阱

外企场景
  • error

    Overcomplicating the solution by not leveraging the hashmap effectively.

  • error

    Not correctly distinguishing between vowels and consonants.

  • error

    Misidentifying edge cases such as strings with no vowels or consonants.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count only vowels and consonants, ignoring other characters in the string.

  • arrow_right_alt

    Consider both uppercase and lowercase letters.

  • arrow_right_alt

    Find the sum of the most frequent letters without distinguishing between vowels and consonants.

help

常见问题

外企场景

找到频率最高的元音和辅音题解:哈希·表·结合·string | LeetCode #3541 简单