LeetCode 题解工作台
奇偶频次间的最大差值 I
给你一个由小写英文字母组成的字符串 s 。 请你找出字符串中两个字符 a 1 和 a 2 的出现频次之间的 最大 差值 diff = freq(a 1 ) - freq(a 2 ) ,这两个字符需要满足: a 1 在字符串中出现 奇数次 。 a 2 在字符串中出现 偶数次 。 返回 最大 差值。 示…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们可以用一个哈希表或数组 记录字符串 中每个字符的出现次数。然后遍历 ,找出出现奇数次的字符的最大频次 和出现偶数次的字符的最小频次 ,最后返回 $a - b$ 即可。 时间复杂度 ,其中 是字符串 的长度。空间复杂度 ,其中 是字符集,本题中 $|\Sigma| = 26$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你一个由小写英文字母组成的字符串 s。
请你找出字符串中两个字符 a1 和 a2 的出现频次之间的 最大 差值 diff = freq(a1) - freq(a2),这两个字符需要满足:
a1在字符串中出现 奇数次 。a2在字符串中出现 偶数次 。
返回 最大 差值。
示例 1:
输入:s = "aaaaabbc"
输出:3
解释:
- 字符
'a'出现 奇数次 ,次数为5;字符'b'出现 偶数次 ,次数为2。 - 最大差值为
5 - 2 = 3。
示例 2:
输入:s = "abcabcab"
输出:1
解释:
- 字符
'a'出现 奇数次 ,次数为3;字符'c'出现 偶数次 ,次数为 2 。 - 最大差值为
3 - 2 = 1。
提示:
3 <= s.length <= 100s仅由小写英文字母组成。s至少由一个出现奇数次的字符和一个出现偶数次的字符组成。
解题思路
方法一:计数
我们可以用一个哈希表或数组 记录字符串 中每个字符的出现次数。然后遍历 ,找出出现奇数次的字符的最大频次 和出现偶数次的字符的最小频次 ,最后返回 即可。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 ,其中 是字符集,本题中 。
class Solution:
def maxDifference(self, s: str) -> int:
cnt = Counter(s)
a, b = 0, inf
for v in cnt.values():
if v % 2:
a = max(a, v)
else:
b = min(b, v)
return a - b
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O( |
面试官常问的追问
外企场景- question_mark
Looking for candidates who can efficiently build a frequency map using a hash table.
- question_mark
Candidates should demonstrate an understanding of the distinction between odd and even frequencies.
- question_mark
Ability to compute the difference between frequencies efficiently is a key signal for success.
常见陷阱
外企场景- error
Candidates may confuse the calculation of maximum odd and minimum even frequencies.
- error
Forgetting to check both odd and even frequencies could lead to incorrect results.
- error
Candidates might incorrectly handle edge cases where there are multiple odd or even frequencies.
进阶变体
外企场景- arrow_right_alt
Consider a variant where the string contains more than one character with the maximum odd frequency.
- arrow_right_alt
Another variant could be calculating the difference for substrings of the string.
- arrow_right_alt
A variation could involve returning the difference between any odd and any even frequency, not necessarily the maximum odd and minimum even.