4194: 字符串匹配
Time Limit: 1 Sec Memory Limit: 128 MB Submit: 206 Solved: 78
Description
给你两个字符串A,B,请输出B字符串在A字符串中出现了几次。
Input
多组测试数据,每组输入两个字符串。字符串的长度 <= 1000000.
Output
输出B在A中出现的次数。
Sample Input
aaa aa
Sample Output
1
HINT
Source
1 #include <cstdio> 2 #include <cstring> 3 4 const int N = 1000000 + 5; 5 char s[N],t[N]; 6 int lens,lent; 7 8 int next[N]; 9 10 void get_fail() { 11 next[0] = -1; 12 for (int i = 1,j = -1; i < lent; ++ i) { 13 while (j != -1 && t[i] != t[j+1]) j = next[j]; 14 next[i] = s[i] == t[j+1] ? ++ j : j; 15 } 16 } 17 18 int work() { 19 lens = strlen(s); 20 lent = strlen(t); 21 get_fail(); 22 int ret = 0; 23 for (int i = 0,j = -1; i < lens; ++ i) { 24 while (j != -1 && s[i] != t[j+1]) j = next[j]; 25 if (s[i] == t[j+1]) { 26 ++ j; 27 if (j == lent-1) { 28 j = -1; 29 ret ++; 30 } 31 } 32 } 33 return ret; 34 } 35 36 int main() { 37 while (scanf("%s",s) != EOF) { 38 scanf("%s",t); 39 printf("%d\n",work()); 40 } 41 return 0; 42 }
纯粹的kmp(铭神写的,orz)
时间: 2024-10-12 21:07:17