LeetCode 题解工作台
找到频率最高的元音和辅音
给你一个由小写英文字母( 'a' 到 'z' )组成的字符串 s 。你的任务是找出出现频率 最高 的元音( 'a' 、 'e' 、 'i' 、 'o' 、 'u' 中的一个)和出现频率 最高 的辅音(除元音以外的所有字母),并返回这两个频数之和。 注意 :如果有多个元音或辅音具有相同的最高频率,可以…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们先用一个哈希表或者一个长度为 的数组 统计每个字母的出现频率。然后我们遍历这个表,找出元音和辅音中出现频率最高的字母,返回它们的频率之和。 我们可以用一个变量 记录元音的最大频率,另一个变量 记录辅音的最大频率。遍历时,如果当前字母是元音,就更新 ;否则就更新 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你一个由小写英文字母('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 <= 100s只包含小写英文字母
解题思路
方法一:计数
我们先用一个哈希表或者一个长度为 的数组 统计每个字母的出现频率。然后我们遍历这个表,找出元音和辅音中出现频率最高的字母,返回它们的频率之和。
我们可以用一个变量 记录元音的最大频率,另一个变量 记录辅音的最大频率。遍历时,如果当前字母是元音,就更新 ;否则就更新 。
最后返回 即可。
时间复杂度 ,其中 是字符串的长度。空间复杂度 ,其中 是字母表的大小,这里是 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.