题目大意:给你两个字符串,让你求第二个字符串在第一个字符串中出现了几次,注意不能有重叠的区间。
由于这题的数据不大,所以朴素的字符串匹配就能解决问题。
代码如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 char str[1005],substr[1005]; 6 int len1,len2,cnt; 7 char *p,*q; 8 9 int main() 10 { 11 do 12 { 13 cnt=0; 14 scanf("%s",str); 15 if(str[0]=='#') 16 break; 17 scanf("%s",substr); 18 len1=strlen(str); 19 len2=strlen(substr); 20 p=str; 21 q=substr; 22 while(p&&p-str<=len1) //防止p越界 23 { 24 if(strncmp(p,q,len2)==0) 25 { 26 cnt++; 27 if(p+len2-str>=len1-1) //防止p越界 28 break; 29 else 30 p+=len2; 31 } 32 else 33 p++; 34 } 35 printf("%d\n",cnt); 36 }while(1); 37 return 0; 38 }
思想也是最简单的,就是回朔。
当然也可以用KMP算法。
代码如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> char str[1005]; char substr[1005]; int next[1005]; int cnt; void getnext() //得到next数组 { int len=strlen(substr); next[0]=-1; int j=-1; for(int i=1;i<len;i++) { while(substr[j+1]!=substr[i]&&j>=0) j=next[j]; if(substr[j+1]==substr[i]) { next[i]=j+1; j++; } else next[i]=-1; } } void getans() { int len1=strlen(str),len2=strlen(substr); int j=-1; for(int i=0;i<len1;i++) { while(str[i]!=substr[j+1]&&j>=0) j=next[j]; if(str[i]==substr[j+1]) { j++; if(j==len2-1) //匹配成功后的操作 { j=-1; //把j设为-1这样就能继续寻找 cnt++; } } } printf("%d\n",cnt); } int main() { do { cnt=0; scanf("%s",str); if(str[0]=='#') break; scanf("%s",substr); getnext(); getans(); }while(1); //system("pause"); return 0; }
思想也就不多说了,KMP嘛!