2207. 字符串中最多数目的子序列
题目描述
给你一个下标从 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 <= 105
pattern.length == 2
text
和pattern
都只包含小写英文字母。
解法
方法一:遍历 + 计数
我们可以使用两个变量 $x$ 和 $y$ 分别记录当前字符串中 $\textit{pattern}[0]$ 和 $\textit{pattern}[1]$ 出现的次数。
然后遍历字符串 $\textit{text}$,对于当前遍历到的字符 $c$:
如果 $c$ 等于 $\textit{pattern}[1]$,我们将 $y$ 加一,此时之前出现过的所有 $\textit{pattern}[0]$ 都可以和当前的 $c$ 组成一个 $\textit{pattern}$ 子序列,因此答案加上 $x$;
如果 $c$ 等于 $\textit{pattern}[0]$,我们将 $x$ 加一。
遍历结束后,由于我们可以插入一个字符,因此,如果我们在字符串开头加上 $\textit{pattern}[0]$,那么可以得到 $y$ 个 $\textit{pattern}$ 子序列;如果我们在字符串结尾加上 $\textit{pattern}[1]$,那么可以得到 $x$ 个 $\textit{pattern}$ 子序列。因此,我们将答案加上 $x$ 和 $y$ 中的较大值即可。
时间复杂度 $O(n)$,其中 $n$ 为字符串 $\textit{text}$ 的长度。空间复杂度 $O(1)$。
Python3
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
Java
class Solution {
public long maximumSubsequenceCount(String text, String pattern) {
long ans = 0;
int x = 0, y = 0;
for (int i = 0; i < text.length(); ++i) {
if (text.charAt(i) == pattern.charAt(1)) {
++y;
ans += x;
}
if (text.charAt(i) == pattern.charAt(0)) {
++x;
}
}
ans += Math.max(x, y);
return ans;
}
}
C++
class Solution {
public:
long long maximumSubsequenceCount(string text, string pattern) {
long long ans = 0;
int x = 0, y = 0;
for (char& c : text) {
if (c == pattern[1]) {
++y;
ans += x;
}
if (c == pattern[0]) {
++x;
}
}
ans += max(x, y);
return ans;
}
};
Go
func maximumSubsequenceCount(text string, pattern string) (ans int64) {
x, y := 0, 0
for _, c := range text {
if byte(c) == pattern[1] {
y++
ans += int64(x)
}
if byte(c) == pattern[0] {
x++
}
}
ans += int64(max(x, y))
return
}
TypeScript
function maximumSubsequenceCount(text: string, pattern: string): number {
let ans = 0;
let [x, y] = [0, 0];
for (const c of text) {
if (c === pattern[1]) {
++y;
ans += x;
}
if (c === pattern[0]) {
++x;
}
}
ans += Math.max(x, y);
return ans;
}