LeetCode 题解工作台

分割字符频率相等的最少子字符串

给你一个字符串 s ,你需要将它分割成一个或者更多的 平衡 子字符串。比方说, s == "ababcc" 那么 ("abab", "c", "c") , ("ab", "abc", "c") 和 ("ababcc") 都是合法分割,但是 ("a", "bab" , "cc") , ( "aba" …

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们设计一个函数 ,表示从字符串 开始分割的最少子字符串数量。那么答案就是 。 函数 的计算过程如下:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 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 <= 1000
  • s 只包含小写英文字母。
lightbulb

解题思路

方法一:记忆化搜索 + 哈希表

我们设计一个函数 dfs(i)\textit{dfs}(i),表示从字符串 s[i]s[i] 开始分割的最少子字符串数量。那么答案就是 dfs(0)\textit{dfs}(0)

函数 dfs(i)\textit{dfs}(i) 的计算过程如下:

如果 ini \geq n,表示已经处理完了所有字符,返回 00

否则,我们维护一个哈希表 cnt\textit{cnt},表示当前子字符串中每个字符出现的次数。另外,我们还维护一个哈希表 freq\textit{freq},表示每个字符出现的次数的频率。

然后我们枚举 jjiin1n-1,表示当前子字符串的结束位置。对于每个 jj,我们更新 cnt\textit{cnt}freq\textit{freq},然后判断 freq\textit{freq} 的大小是否为 11,如果是的话,我们可以从 j+1j+1 开始分割,此时答案为 1+dfs(j+1)1 + \textit{dfs}(j+1),我们取所有 jj 中答案的最小值作为函数的返回值。

为了避免重复计算,我们使用记忆化搜索。

时间复杂度 O(n2)O(n^2),空间复杂度 O(n×Σ)O(n \times |\Sigma|)。其中 nn 为字符串 ss 的长度,而 Σ|\Sigma| 表示字符集的大小,本题中 Σ=26|\Sigma| = 26

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

分割字符频率相等的最少子字符串题解:状态·转移·动态规划 | LeetCode #3144 中等