LeetCode 题解工作台

奇偶频次间的最大差值 I

给你一个由小写英文字母组成的字符串 s 。 请你找出字符串中两个字符 a 1 和 a 2 的出现频次之间的 最大 差值 diff = freq(a 1 ) - freq(a 2 ) ,这两个字符需要满足: a 1 在字符串中出现 奇数次 。 a 2 在字符串中出现 偶数次 。 返回 最大 差值。 示…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

我们可以用一个哈希表或数组 记录字符串 中每个字符的出现次数。然后遍历 ,找出出现奇数次的字符的最大频次 和出现偶数次的字符的最小频次 ,最后返回 $a - b$ 即可。 时间复杂度 ,其中 是字符串 的长度。空间复杂度 ,其中 是字符集,本题中 $|\Sigma| = 26$。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由小写英文字母组成的字符串 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 <= 100
  • s 仅由小写英文字母组成。
  • s 至少由一个出现奇数次的字符和一个出现偶数次的字符组成。
lightbulb

解题思路

方法一:计数

我们可以用一个哈希表或数组 cnt\textit{cnt} 记录字符串 ss 中每个字符的出现次数。然后遍历 cnt\textit{cnt},找出出现奇数次的字符的最大频次 aa 和出现偶数次的字符的最小频次 bb,最后返回 aba - b 即可。

时间复杂度 O(n)O(n),其中 nn 是字符串 ss 的长度。空间复杂度 O(Σ)O(|\Sigma|),其中 Σ\Sigma 是字符集,本题中 Σ=26|\Sigma| = 26

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

指标
时间O(n)
空间O(
psychology

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

奇偶频次间的最大差值 I题解:哈希·表·结合·string | LeetCode #3442 简单