标签:没有 pre names char ios har style 出现 iostream
abcde a3 aaaaaa aa #Sample Output
0 3
第一次学习kmp,然后根据理解,做了一下这个题,用c做的
#include <stdio.h> #include <stdlib.h> #include <string.h> void findnext(char *str,int next[],int size) { int k = -1,i = 1; next[0] = -1; while(i < size) { while(k != -1 && str[k + 1] != str[i])k = next[k]; if(str[k + 1] == str[i])k ++; next[i ++] = k; } } int kmp(char *s,int ssize,char *p,int psize) { int next[1000],ans = 0; findnext(p,next,psize); // for(int i = 0;i < psize;i ++) // printf("%d ",next[i]); int k = -1,i = -1; while(++ i < ssize) { while(k != -1 && p[k + 1] != s[i])k = next[k]; if(p[k + 1] == s[i])k ++; if(k == psize - 1)ans ++,k = -1; } return ans; } int main() { char s[1000],p[1000]; while(~scanf("%s",s)&&strcmp(s,"#")) { scanf("%s",p); printf("%d\n",kmp(s,strlen(s),p,strlen(p))); } }
用c++ string类写了一下,不用像kmp考虑那么累
代码:
#include <iostream> #include <string> using namespace std; int check(string a,string b) { int d = b.size(),ans = 0; int size = a.size() - d + 1; string t; for(int i = 0;i <= size;i ++) { if(a[i] == b[0]) { t.assign(a,i,d); if(t == b) { ans ++; i += d - 1; } } } return ans; } int main() { string a,b; while(cin>>a&&a!="#") { cin>>b; cout<<check(a,b)<<endl; } }
标签:没有 pre names char ios har style 出现 iostream
原文地址:http://www.cnblogs.com/8023spz/p/7764305.html