【尺取】String hdoj 5672(字串追趕)
阿新 • • 發佈:2019-02-14
String hdoj 5672(字串追趕)
題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=5672
題目解析
對於每一個左邊界,只要找到最小的滿足條件的右邊界,就能在O(1)時間內統計完所有以這個左邊界開始的符合條件的子串。
尋找這個右邊界,是經典的追趕法(尺取法,雙指標法)問題。維護兩個指標(陣列下標),輪流更新左右邊界,同時累加答案即可
ac程式碼
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
int a[27];
char s[1000010];
int main()
{
int k,t;
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
scanf("%d",&k);
int len=strlen(s);
long long sum=0;
int x=0,y=0,num=0;
memset(a,0,sizeof(a));
while(1)
{
while (y<len && num<k)
{
int f = s[y++] - 'a';
if(a[f] == 0)
num++;
a[f]++;
}
if(num < k)
break;
sum+=len-y+1;
a[s[x] - 'a']--;
if(a[s[x] - 'a' ] == 0)
num--;
x++;
}
printf("%lld\n",sum);
}
return 0;
}