👨🏫 Acwing 字串简写
输入
4
abababdb a b
输出
6
💖 前缀和
import java.util.Scanner;
public class Main
{
static int N = (int) 5e5 + 10;
static int[] l = new int[N];// l[i] 表示 i 以及 i 左边包含多少个字符 a
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
String s = sc.next();
s = "0" + s;//占位符,下标为 0 不用
char a = sc.next().charAt(0);
char b = sc.next().charAt(0);
char[] ss = s.toCharArray();
int n = ss.length;
l[0] = 0;
//处理前缀和数组
for (int i = 1; i < n; i++)
{
l[i] = l[i - 1];
if (ss[i] == a)
l[i]++;
}
long ans = 0;
for (int i = 0; i < n; i++)
// 从第k个开始处理
if (i >= k && ss[i] == b)
{
ans += l[i - k + 1];
}
System.out.println(ans);
}
}