Substring Frequency LightOJ - 1255
转载请注明出处,谢谢。http://www.cnblogs.com/acmer-roney/---by Roney
Time Limit: 1000MS | Memory Limit: 65536KB | 64bit IO Format: %lld & %llu |
Description
A string is a finite sequence of symbols that are chosen from an alphabet. In this problem you are given two non-empty strings A and B, both contain lower case English alphabets. You have to find the number of times B occurs as a substring of A.
Input
Input starts with an integer T (≤ 5), denoting the number of test cases.
Each case starts with two lines. First line contains A and second line contains B. You can assume than 1 ≤ length(A), length(B) ≤ 106.
Output
For each case, print the case number and the number of times B occurs as a substring of A.
Sample Input
4
axbyczd
abc
abcabcabcabc
abc
aabacbaabbaaz
aab
aaaaaa
aa
Sample Output
Case 1: 0
Case 2: 4
Case 3: 2
Case 4: 5
题目连接: http://acm.hust.edu.cn:8080/judge/problem/viewProblem.action?id=26965
解题思路:做此题一定要对KMP的next[]数组有充分的理解。针对此题,当匹配成功后,对计数器ans加一,并当作匹配失败处理,即执行j=next[j],继续和主串进行匹配。
注意:此题的next[]数组是用修正前的next[]数组!
AC代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<cstring> 3 #define N 1000001 4 char s1[N],s2[N]; 5 int next[N]; 6 int len1,len2; 7 void getnext() 8 { 9 int j=0,k=-1; 10 next[0]=-1; 11 len2=strlen(s2); 12 while(j<len2){ 13 if(k==-1||s2[j]==s2[k]){ 14 j++;k++; 15 if(s2[j]!=s2[k])next[j]=k; 16 else next[j]=next[k]; 17 } 18 else k=next[k]; 19 } 20 } 21 int kmp() 22 { 23 getnext(); 24 int i=0,j=0,ans=0; 25 len1=strlen(s1); 26 while(i<len1){ 27 if(j==-1||s1[i]==s2[j]){ 28 i++;j++; 29 if(j>=len2){ 30 j=next[j]; 31 ans++; 32 } 33 } 34 else j=next[j]; 35 } 36 return ans; 37 } 38 int main() 39 { 40 //freopen("in.txt","r",stdin); 41 int t,c=0;scanf("%d",&t); 42 while(t--){ 43 scanf("%s %s",s1,s2); 44 printf("Case %d: %d\n",++c,kmp()); 45 } 46 return 0; 47 }
posted on 2012-09-07 22:00 Acmer_Roney 阅读(268) 评论(0) 编辑 收藏 举报