|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
看小甲鱼的kmp看了一晚上明白了不少但优化- #include<iostream>
- #include<cstring>
- using namespace std;
- int get_next(string t,int next[])
- {
- int i=1;
- int j=0;
- next[1]=0;
-
- while(i<t[0])
- {
- if(j==0 || t[i]==t[j])
- {
- i++;
- j++;
- //next[i]=j;
- if(t[i]!=t[j])
- {
- next[i]=j;
- }
- else
- {
- next[i]=next[j];
- }
- }
- else
- {
- j=next[j];
- }
- }
- }
- int index_kmp(string s,string t,int pos)
- {
- int i=pos;
- int j=1;
- int next[255];
- get_next(t,next);
-
- while(i<=s[0]&&j<=t[0])
- {
- if(0==j || s[i]==t[j])
- {
- i++;
- j++;
- }
- else
- {
- j=next[j];
- }
- }
-
- if(j>t[0])
- return i-t[0];
- else
- return 0;
- }
- int main()
- {
- char s[255]=" sddsfdsfsfsfefe";
- char t[25]=" fds";
-
- s[0]=strlen(s)-1;
- t[0]=strlen(t)-1;
-
- cout<<index_kmp(s,t,1);
- return 0;
- }
复制代码
那里还是不太清楚 不能不把代码粘上来
|
|