LeetCode 题解工作台

使字符频率相等的最少操作次数

给你一个字符串 s 。 如果字符串 t 中的字符出现次数相等,那么我们称 t 为 好的 。 你可以执行以下操作 任意次 : 从 s 中删除一个字符。 往 s 中添加一个字符。 将 s 中一个字母变成字母表中下一个字母。 注意 ,第三个操作不能将 'z' 变为 'a' 。 请你返回将 s 变 好 的 …

category

5

题型

code_blocks

0

代码语言

hub

3

相关题

当前训练重点

困难 · 状态·转移·动态规划

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s 。

如果字符串 t 中的字符出现次数相等,那么我们称 t 为 好的 。

你可以执行以下操作 任意次 :

  • 从 s 中删除一个字符。
  • 往 s 中添加一个字符。
  • 将 s 中一个字母变成字母表中下一个字母。

注意 ,第三个操作不能将 'z' 变为 'a' 。

请你返回将 s 变  的 最少 操作次数。

 

示例 1:

输入:s = "acab"

输出:1

解释:

删掉一个字符 'a' ,s 变为好的。

示例 2:

输入:s = "wddw"

输出:0

解释:

s 一开始就是好的,所以不需要执行任何操作。

示例 3:

输入:s = "aaabc"

输出:2

解释:

通过以下操作,将 s 变好:

  • 将一个 'a' 变为 'b' 。
  • s 中插入一个 'c' 。

 

提示:

  • 1 <= s.length <= 2 * 104
  • s 只包含小写英文字母。
lightbulb

解题思路

方法一

1
2

speed

复杂度分析

指标
时间complexity depends on the number of unique character frequencies and DP state transitions, roughly O(n log n) for counting and sorting plus frequency adjustment iterations. Space complexity is dominated by hash table storage and DP table, typically O(n) for character counts.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for correct use of hash table to tally character frequencies.

  • question_mark

    Check if candidate properly applies dynamic programming for state transitions between frequency reductions.

  • question_mark

    Assess awareness of trade-offs between deleting excess characters versus leaving frequencies uneven.

warning

常见陷阱

外企场景
  • error

    Failing to account for multiple characters sharing the same frequency, leading to incorrect minimal deletions.

  • error

    Overcomplicating the DP by considering unnecessary permutations of character deletions.

  • error

    Neglecting edge cases where all characters already have equal frequency, resulting in extra operations.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to allow incrementing character counts instead of only deletions.

  • arrow_right_alt

    Restrict the string to only vowels and optimize deletions to equalize their frequencies.

  • arrow_right_alt

    Introduce a maximum allowed deletion limit and find if making frequencies equal is possible under that constraint.

help

常见问题

外企场景

使字符频率相等的最少操作次数题解:状态·转移·动态规划 | LeetCode #3389 困难