LeetCode 题解工作台
替换子串得到平衡字符串
有一个只含有 'Q', 'W', 'E', 'R' 四种字符,且长度为 n 的字符串。 假如在该字符串中,这四个字符都恰好出现 n/4 次,那么它就是一个「平衡字符串」。 给你一个这样的字符串 s ,请通过「替换一个子串」的方式,使原字符串 s 变成一个「平衡字符串」。 你可以用和「待替换子串」长度…
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 滑动窗口(状态滚动更新)
答案摘要
我们先用一个哈希表或数组 `cnt` 统计字符串 中每个字符的数量,如果所有字符的数量都不超过 ,那么字符串 就是平衡字符串,直接返回 。 否则,我们使用双指针 和 分别维护窗口的左右边界,初始时 $j = 0$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
有一个只含有 'Q', 'W', 'E', 'R' 四种字符,且长度为 n 的字符串。
假如在该字符串中,这四个字符都恰好出现 n/4 次,那么它就是一个「平衡字符串」。
给你一个这样的字符串 s,请通过「替换一个子串」的方式,使原字符串 s 变成一个「平衡字符串」。
你可以用和「待替换子串」长度相同的 任何 其他字符串来完成替换。
请返回待替换子串的最小可能长度。
如果原字符串自身就是一个平衡字符串,则返回 0。
示例 1:
输入:s = "QWER" 输出:0 解释:s 已经是平衡的了。
示例 2:
输入:s = "QQWE" 输出:1 解释:我们需要把一个 'Q' 替换成 'R',这样得到的 "RQWE" (或 "QRWE") 是平衡的。
示例 3:
输入:s = "QQQW" 输出:2 解释:我们可以把前面的 "QQ" 替换成 "ER"。
示例 4:
输入:s = "QQQQ" 输出:3 解释:我们可以替换后 3 个 'Q',使 s = "QWER"。
提示:
1 <= s.length <= 10^5s.length是4的倍数s中只含有'Q','W','E','R'四种字符
解题思路
方法一:计数 + 双指针
我们先用一个哈希表或数组 cnt 统计字符串 中每个字符的数量,如果所有字符的数量都不超过 ,那么字符串 就是平衡字符串,直接返回 。
否则,我们使用双指针 和 分别维护窗口的左右边界,初始时 。
接下来,从左到右遍历字符串 ,每次遍历到一个字符,就将该字符的数量减 ,然后判断当前窗口是否满足条件,即窗口外的字符数量都不超过 。如果满足条件,那么就更新答案,然后将窗口的左边界右移,直到不满足条件为止。
最后,返回答案即可。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度;而 是字符集的大小,本题中 。
class Solution:
def balancedString(self, s: str) -> int:
cnt = Counter(s)
n = len(s)
if all(v <= n // 4 for v in cnt.values()):
return 0
ans, j = n, 0
for i, c in enumerate(s):
cnt[c] -= 1
while j <= i and all(v <= n // 4 for v in cnt.values()):
ans = min(ans, i - j + 1)
cnt[s[j]] += 1
j += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each character is processed at most twice while sliding the window. Space complexity is O(1) due to the fixed-size character frequency map for 'Q', 'W', 'E', and 'R'. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate should recognize the need for a sliding window instead of brute-force substring checks.
- question_mark
Optimal solutions involve counting characters outside the window, not inside it, to simplify validation.
- question_mark
Tracking excess frequencies dynamically is a key optimization for linear-time performance.
常见陷阱
外企场景- error
Forgetting to handle the case when the string is already balanced, returning a non-zero length incorrectly.
- error
Incorrectly updating counts when moving the window, leading to invalid balance checks.
- error
Assuming replacement must be of specific characters instead of any string of the same length.
进阶变体
外企场景- arrow_right_alt
Determine maximum substring length that can be replaced without unbalancing the string.
- arrow_right_alt
Extend to strings with k distinct characters instead of exactly 4.
- arrow_right_alt
Find the minimum replacement substring when balancing requires exactly m occurrences per character instead of n/4.