ProblemC 剪花布条(KMP基础)
题目大意:
就是说,给你一个文本串,给你一个模式串,然后让你求出模式串在文本串中出现了多少次,注意,不能有重叠.
解题思路:
把在文本串中找模式串的程序稍微修改下,就A了,把t2=next[t2] 改为0,就好了。
代码:
1 # include<cstdio> 2 # include<iostream> 3 # include<cstring> 4 5 using namespace std; 6 7 # define MAX 1234 8 9 char s1[MAX]; 10 char s2[MAX]; 11 int nxt[MAX]; 12 13 void get_nxt() 14 { 15 int len = strlen(s2); 16 int t1 = 0,t2; 17 t2 = nxt[0] = -1; 18 while ( t1 < len ) 19 { 20 if ( t2==-1||s2[t1]==s2[t2] ) 21 { 22 t1++;t2++; 23 nxt[t1] = t2; 24 } 25 else 26 t2 = nxt[t2]; 27 } 28 } 29 30 int kmp() 31 { 32 int len1 = strlen(s1), len2 = strlen(s2); 33 int t1 = 0,t2 = 0; 34 int times = 0; 35 while ( t1<len1 ) 36 { 37 if ( t2==-1||s1[t1]==s2[t2] ) 38 { 39 t1++;t2++; 40 } 41 else 42 t2 = nxt[t2]; 43 if ( t2==len2 ) 44 { 45 times+=1; 46 t2 = 0; 47 } 48 } 49 return times; 50 } 51 52 int main(void) 53 { 54 while ( scanf("%s%s",s1,s2) ) 55 { 56 if ( s1[0]=='#' ) 57 break; 58 get_nxt(); 59 int ans = kmp(); 60 printf("%d\n",ans); 61 } 62 63 return 0; 64 }