Topic Links: http://acm.hdu.edu.cn/showproblem.php?pid=2087
KMP Template title :
#include <cstdio>#include<cstring>#include<iostream>using namespacestd;#defineN 1100CharS1[n], s2[n];intP[n], L1, L2;voidGetp () {intI=0, j=-1; p[0] = -1; while(i<L2) { if(j==-1|| s2[i]==S2[j]) {i++;j++; P[i]=J; } ElseJ=P[j]; }}intKMP () {intI=0, j=0, ans =0; while(i<L1) { if(j==-1|| S1[i] = =S2[j]) {i++; J++; } Else{J=P[j]; } if(j==L2) {ans++; J=0; } } returnans;}intMain () { while(SCANF ("%s%s", s1, S2), strcmp (S1,"#") ) {L1=strlen (S1); L2=strlen (S2); GETP (); intAns =KMP (); printf ("%d\n", ans); } return 0;}
KMP
#include <iostream>#include<stdio.h>#include<algorithm>#include<string.h>#defineN 2100using namespacestd;intMain () {CharS1[n],s2[n]; intLen1,len2,i,j,ans; while(SCANF ("%s", S1), strcmp (S1,"#") {scanf ("%s", S2); Len2=strlen (S2); Len1=strlen (S1); if(len1<len2) {printf ("0\n"); Continue; } Else{ans=0; I=j=0; while(1) { if(s1[i]!=S2[j]) I++; while(s1[i]==s2[j]&&j<len2&&i<len1) {i++; J++; } if(j==len2) ans++; if(i==len1) Break; J=0; } printf ("%d\n", ans); } } return 0;}
Common Methods
Cut cloth---hdu2087 (kmp template)