标签:
1 // KMP
2
3 void get_next(char s[],int next[])
4 {
5 int i,j;
6 i=1;j=0;
7 next[1]=0;
8 int len=strlen(s);
9 while(i<len)
10 {
11 if(j==0||s[i-1]==s[j-1])
12 {
13 i++;
14 j++;
15 if(s[i-1]==s[j-1])
16 next[i]=next[j];
17 else
18 next[i]=j;
19 }
20 else
21 j=next[j];
22 }
23 }
24
25 void KMP(char *s,char *t,int pos)// 从s的第pos开始
26 {
get_next(t,next);
27 int i=pos;
28 int j=1;
29 int len1=strlen(s);
30 int len2=strlen(t);
31 while(i<=len1&&j<=len2)
32 {
33 if(j==0||s[i-1]==t[j-1])
34 {
35 i++;
36 j++;
37 }
38 else
39 j=next[j];
40 }
41 if(j>len2)
42 return i-len2-1;
43 else
44 return -1;
45 }
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8818 Accepted Submission(s): 4013
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <string> 7 #include <vector> 8 #include <stack> 9 #include <queue> 10 #include <set> 11 #include <map> 12 #include <iomanip> 13 using namespace std; 14 const int INF=0x5fffffff; 15 const int MS=200005; 16 const double EXP=1e-8; 17 char str1[MS],str2[MS/2]; 18 int next[MS/2]; 19 20 void get_next(char s[],int next[]) 21 { 22 int i,j; 23 i=1;j=0; 24 next[1]=0; 25 int len=strlen(s); 26 while(i<len) 27 { 28 if(j==0||s[i-1]==s[j-1]) 29 { 30 i++; 31 j++; 32 if(s[i-1]==s[j-1]) 33 next[i]=next[j]; 34 else 35 next[i]=j; 36 } 37 else 38 j=next[j]; 39 } 40 } 41 42 int KMP(char *s,char *t,int pos)// 从s的第pos开始 43 { 44 get_next(t,next); 45 int i=pos; 46 int j=1; 47 int len1=strlen(s); 48 int len2=strlen(t); 49 while(i<=len1&&j<=len2) 50 { 51 if(j==0||s[i-1]==t[j-1]) 52 { 53 i++; 54 j++; 55 } 56 else 57 j=next[j]; 58 } 59 if(j>len2) 60 return i-len2-1; 61 else 62 return -1; 63 } 64 65 66 67 int main() 68 { 69 while(scanf("%s%s",str1,str2)!=EOF) 70 { 71 sprintf(str1,"%s%s",str1,str1); 72 /* 73 if(strstr(str1,str2)!=NULL) 74 printf("yes\n"); 75 else 76 printf("no\n"); 77 */ 78 if(KMP(str1,str2,1)>=0) 79 printf("yes\n"); 80 else 81 printf("no\n"); 82 } 83 return 0; 84 }
标签:
原文地址:http://www.cnblogs.com/767355675hutaishi/p/4302485.html