Description
Recently, Norge found a string s=s1s2…sn consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all n(n+1)2 of them!
A substring of s is a non-empty string x=s[a…b]=sasa+1…sb (1≤a≤b≤n). For example, “auto” and “ton” are substrings of “automaton”.
Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only k Latin letters c1,c2,…,ck out of 26.
After that, Norge became interested in how many substrings of the string s he could still type using his broken keyboard. Help him to find this number.
Input
The first line contains two space-separated integers n and k (1≤n≤2⋅10^5, 1≤k≤26) — the length of the string s and the number of Latin letters still available on the keyboard.
The second line contains the string s consisting of exactly n lowercase Latin letters.
The third line contains k space-separated distinct lowercase Latin letters c1,c2,…,ck — the letters still available on the keyboard.
Output
Print a single number — the number of substrings of s that can be typed using only available letters c1,c2,…,ck.
Sample Input
7 2
abacaba
a b
Sample Output
12
换而言之:
给出一个字符串s,定义s的子字符串s1是包含在s中的并且连续的,例如“por”是“import”的子字符串,而“prt”不是。给出k个字符,请你求出可以用这k个字符组合出s所有的子字符串的几个,统计多少个子字符串,在字符串位子不同即可,子串可相同,且子串字母必须是最后一次输入的字母中。
例如输入例子:abacaba
s[1-2],s[2-3],s[1-3],s[1-1],s[2-2],s[3-3],s[5-6],s[6-7],s[5-7],s[5-5],s[6-6],s[7-7]共12中
思路:统计每个最大连续最大子串字符个数temp,然后temp*(temp-1))/2可以求每个最大子字符串可得到多少个连续符合要求的子字符串,最后ans累加输出即可。
代码思路:
1、定义a、b输入字符串字母的个数,与子字符串字母库的个数
2、定义char数组c和d分别保存字符串和子字符串字母库
3、对c字符串的每个字符和d子字符串字母库进行对比,找不到则证明当前temp已经是某个最大连续子字符串,进行temp*(temp-1))/2
4、ans累加输出
注意:本题虽然是水题,但是有一个坑,根据(1≤n≤2⋅10^5, 1≤k≤26)的范围可知,ans结果可能非常大,超出int范围,所以需要用到long long
ac代码:
#include<stdio.h>
int main()
{
long long a,b,ans=0,f=0,temp=0;
char c[200001],d[100];
scanf("%lld %lld",&a,&b);
scanf("%s",&c);
for(int i=0;i<b;i++)//输入参照字符库
{
scanf("%s",&d[i]);
}
for(int i=0;i<a;i++)//对c字符串字符逐个对比b
{
for(int j=0;j<b;j++)
{
if(c[i]==d[j])//判断字符是否是参照字符库的字母
{
f=1;
break;
}
}
if(f==1)//是,temp++,重新判断
{
temp++;
f=0;
}
else//不是,ans累计,重新统计temp
{
ans=ans+(temp*(temp+1))/2;
temp=0;
}
}
ans=ans+(temp*(temp+1))/2;
printf("%lld",ans);
return 0;
}