LeetCode 题解工作台
分割字符频率相等的最少子字符串
给你一个字符串 s ,你需要将它分割成一个或者更多的 平衡 子字符串。比方说, s == "ababcc" 那么 ("abab", "c", "c") , ("ab", "abc", "c") 和 ("ababcc") 都是合法分割,但是 ("a", "bab" , "cc") , ( "aba" …
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们设计一个函数 ,表示从字符串 开始分割的最少子字符串数量。那么答案就是 。 函数 的计算过程如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个字符串 s ,你需要将它分割成一个或者更多的 平衡 子字符串。比方说,s == "ababcc" 那么 ("abab", "c", "c") ,("ab", "abc", "c") 和 ("ababcc") 都是合法分割,但是 ("a", "bab", "cc") ,("aba", "bc", "c") 和 ("ab", "abcc") 不是,不平衡的子字符串用粗体表示。
请你返回 s 最少 能分割成多少个平衡子字符串。
注意:一个 平衡 字符串指的是字符串中所有字符出现的次数都相同。
示例 1:
输入:s = "fabccddg"
输出:3
解释:
我们可以将 s 分割成 3 个子字符串:("fab, "ccdd", "g") 或者 ("fabc", "cd", "dg") 。
示例 2:
输入:s = "abababaccddb"
输出:2
解释:
我们可以将 s 分割成 2 个子字符串:("abab", "abaccddb") 。
提示:
1 <= s.length <= 1000s只包含小写英文字母。
解题思路
方法一:记忆化搜索 + 哈希表
我们设计一个函数 ,表示从字符串 开始分割的最少子字符串数量。那么答案就是 。
函数 的计算过程如下:
如果 ,表示已经处理完了所有字符,返回 。
否则,我们维护一个哈希表 ,表示当前子字符串中每个字符出现的次数。另外,我们还维护一个哈希表 ,表示每个字符出现的次数的频率。
然后我们枚举 从 到 ,表示当前子字符串的结束位置。对于每个 ,我们更新 和 ,然后判断 的大小是否为 ,如果是的话,我们可以从 开始分割,此时答案为 ,我们取所有 中答案的最小值作为函数的返回值。
为了避免重复计算,我们使用记忆化搜索。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度,而 表示字符集的大小,本题中 。
class Solution:
def minimumSubstringsInPartition(self, s: str) -> int:
@cache
def dfs(i: int) -> int:
if i >= n:
return 0
cnt = defaultdict(int)
freq = defaultdict(int)
ans = n - i
for j in range(i, n):
if cnt[s[j]]:
freq[cnt[s[j]]] -= 1
if not freq[cnt[s[j]]]:
freq.pop(cnt[s[j]])
cnt[s[j]] += 1
freq[cnt[s[j]]] += 1
if len(freq) == 1 and (t := 1 + dfs(j + 1)) < ans:
ans = t
return ans
n = len(s)
return dfs(0)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate should demonstrate an understanding of dynamic programming and its applications to partitioning problems.
- question_mark
Look for understanding of how state transitions in DP work, especially how to handle the frequency distributions.
- question_mark
Check if the candidate optimizes the solution using hash tables to manage character counts effectively.
常见陷阱
外企场景- error
Failing to recognize that the problem requires checking character frequency distributions across partitions.
- error
Misunderstanding the DP state transition, particularly how to track and update dp[i] values correctly.
- error
Inefficient handling of the string with brute-force approaches that don't make use of dynamic programming or sliding windows.
进阶变体
外企场景- arrow_right_alt
Implementing this problem with a greedy approach may miss valid partitions and lead to incorrect results.
- arrow_right_alt
A brute-force solution can become inefficient for longer strings, especially when dealing with up to 1000 characters.
- arrow_right_alt
Trying to solve without using dynamic programming will lead to higher time complexities and possible redundant calculations.