LeetCode 题解工作台
字符串中最多数目的子序列
给你一个下标从 0 开始的字符串 text 和另一个下标从 0 开始且长度为 2 的字符串 pattern ,两者都只包含小写英文字母。 你可以在 text 中任意位置插入 一个 字符,这个插入的字符必须是 pattern[0] 或者 pattern[1] 。注意,这个字符可以插入在 text 开头…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们可以使用两个变量 和 分别记录当前字符串中 和 出现的次数。 然后遍历字符串 ,对于当前遍历到的字符 :
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个下标从 0 开始的字符串 text 和另一个下标从 0 开始且长度为 2 的字符串 pattern ,两者都只包含小写英文字母。
你可以在 text 中任意位置插入 一个 字符,这个插入的字符必须是 pattern[0] 或者 pattern[1] 。注意,这个字符可以插入在 text 开头或者结尾的位置。
请你返回插入一个字符后,text 中最多包含多少个等于 pattern 的 子序列 。
子序列 指的是将一个字符串删除若干个字符后(也可以不删除),剩余字符保持原本顺序得到的字符串。
示例 1:
输入:text = "abdcdbc", pattern = "ac" 输出:4 解释: 如果我们在 text[1] 和 text[2] 之间添加 pattern[0] = 'a' ,那么我们得到 "abadcdbc" 。那么 "ac" 作为子序列出现 4 次。 其他得到 4 个 "ac" 子序列的方案还有 "aabdcdbc" 和 "abdacdbc" 。 但是,"abdcadbc" ,"abdccdbc" 和 "abdcdbcc" 这些字符串虽然是可行的插入方案,但是只出现了 3 次 "ac" 子序列,所以不是最优解。 可以证明插入一个字符后,无法得到超过 4 个 "ac" 子序列。
示例 2:
输入:text = "aabb", pattern = "ab" 输出:6 解释: 可以得到 6 个 "ab" 子序列的部分方案为 "aaabb" ,"aaabb" 和 "aabbb" 。
提示:
1 <= text.length <= 105pattern.length == 2text和pattern都只包含小写英文字母。
解题思路
方法一:遍历 + 计数
我们可以使用两个变量 和 分别记录当前字符串中 和 出现的次数。
然后遍历字符串 ,对于当前遍历到的字符 :
- 如果 等于 ,我们将 加一,此时之前出现过的所有 都可以和当前的 组成一个 子序列,因此答案加上 ;
- 如果 等于 ,我们将 加一。
遍历结束后,由于我们可以插入一个字符,因此,如果我们在字符串开头加上 ,那么可以得到 个 子序列;如果我们在字符串结尾加上 ,那么可以得到 个 子序列。因此,我们将答案加上 和 中的较大值即可。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
class Solution:
def maximumSubsequenceCount(self, text: str, pattern: str) -> int:
ans = x = y = 0
for c in text:
if c == pattern[1]:
y += 1
ans += x
if c == pattern[0]:
x += 1
ans += max(x, y)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate effectively demonstrates the ability to apply a greedy approach for subsequences.
- question_mark
The candidate uses prefix sums or dynamic counting to reduce time complexity in their solution.
- question_mark
The candidate ensures the optimal placement of characters using invariant validation, avoiding suboptimal solutions.
常见陷阱
外企场景- error
Not considering the best position to insert the character, which leads to suboptimal solutions.
- error
Failing to handle edge cases such as when inserting at the beginning or end of the string.
- error
Misunderstanding how subsequences are counted and invalidating potential subsequences after insertion.
进阶变体
外企场景- arrow_right_alt
What happens if the pattern length is greater than 2?
- arrow_right_alt
Can the pattern contain repeated characters and still maintain the same approach?
- arrow_right_alt
What if the pattern length increases dynamically during the insertion?