LeetCode 题解工作台
最大波动的子字符串
字符串的 波动 定义为子字符串中出现次数 最多 的字符次数与出现次数 最少 的字符次数之差。 给你一个字符串 s ,它只包含小写英文字母。请你返回 s 里所有 子字符串的 最大波动 值。 子字符串 是一个字符串的一段连续字符序列。 示例 1: 输入: s = "aababbb" 输出: 3 解释: …
2
题型
5
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
由于字符集只包含小写字母,我们可以考虑枚举出现次数最多的字符 以及出现次数最少的字符 。对于一个子串来说,这两种字符出现的次数之差就是子串的波动值。 具体实现上,我们使用双重循环枚举 和 ,用 记录以当前字符结尾的连续出现字符 的个数,用 记录以当前字符结尾的,并且包含 和 的子串的波动值。迭代取 的最大值即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
字符串的 波动 定义为子字符串中出现次数 最多 的字符次数与出现次数 最少 的字符次数之差。
给你一个字符串 s ,它只包含小写英文字母。请你返回 s 里所有 子字符串的 最大波动 值。
子字符串 是一个字符串的一段连续字符序列。
示例 1:
输入:s = "aababbb" 输出:3 解释: 所有可能的波动值和它们对应的子字符串如以下所示: - 波动值为 0 的子字符串:"a" ,"aa" ,"ab" ,"abab" ,"aababb" ,"ba" ,"b" ,"bb" 和 "bbb" 。 - 波动值为 1 的子字符串:"aab" ,"aba" ,"abb" ,"aabab" ,"ababb" ,"aababbb" 和 "bab" 。 - 波动值为 2 的子字符串:"aaba" ,"ababbb" ,"abbb" 和 "babb" 。 - 波动值为 3 的子字符串 "babbb" 。 所以,最大可能波动值为 3 。
示例 2:
输入:s = "abcde" 输出:0 解释: s 中没有字母出现超过 1 次,所以 s 中每个子字符串的波动值都是 0 。
提示:
1 <= s.length <= 104s只包含小写英文字母。
解题思路
方法一:枚举 + 动态规划
由于字符集只包含小写字母,我们可以考虑枚举出现次数最多的字符 以及出现次数最少的字符 。对于一个子串来说,这两种字符出现的次数之差就是子串的波动值。
具体实现上,我们使用双重循环枚举 和 ,用 记录以当前字符结尾的连续出现字符 的个数,用 记录以当前字符结尾的,并且包含 和 的子串的波动值。迭代取 的最大值即可。
递推公式如下:
- 如果当前字符为 ,则 和 都加 ;
- 如果当前字符为 ,则 ,而 ;
- 否则,无需考虑。
注意,初始时将 赋值为一个负数最大值,可以保证更新答案时是合法的。
时间复杂度 ,其中 是字符串长度,而 是字符集大小。空间复杂度 。
class Solution:
def largestVariance(self, s: str) -> int:
ans = 0
for a, b in permutations(ascii_lowercase, 2):
if a == b:
continue
f = [0, -inf]
for c in s:
if c == a:
f[0], f[1] = f[0] + 1, f[1] + 1
elif c == b:
f[1] = max(f[1] - 1, f[0] - 1)
f[0] = 0
if ans < f[1]:
ans = f[1]
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \cdot k^2) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Look for understanding of dynamic programming and state transitions.
- question_mark
Check if the candidate can optimize by considering only two characters initially.
- question_mark
Assess whether the candidate uses iterative updates to minimize redundant calculations.
常见陷阱
外企场景- error
Forgetting to optimize by limiting the number of distinct characters considered initially.
- error
Overcomplicating the solution by recalculating character frequencies for every substring.
- error
Neglecting the importance of updating states incrementally in dynamic programming.
进阶变体
外企场景- arrow_right_alt
What if the string contains more than two characters? Extend the solution to account for all characters while maintaining efficiency.
- arrow_right_alt
Consider solving the problem without using dynamic programming and assess the trade-offs in terms of time complexity.
- arrow_right_alt
Explore edge cases where the string is very short or where all characters are identical.