<pre name="code" class="cpp"><span style="background-color: rgb(0, 153, 0);"><span style="font-size:14px;">题目要求:</span></span>
用KMP算法实现查找子串在母串中的位置。
<span style="background-color: rgb(0, 153, 0);"><span style="font-size:14px;">代码实现:</span></span>
<pre name="code" class="cpp">
#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
void print(int n)
{
cout<<n<<'\0';
}
*/
int find_substring(string pattern, string text)
{
int n = (pattern.size()-1);
vector<int>next(n+1, 0);
int i=1,j=0;
while(i<n)
{
if (j==0||pattern[i]==pattern[j])
{
++i;
++j;
if(pattern[i]!=pattern[j])
next[i]=j;
else
next[i]=next[j];
cout<<"asdfa:"<<i<<":"<<next[i]<<endl;
}
else
j=next[j];
}
//vector<int>::iterator itor;
//for_each(next.begin(),next.end(),print);//用for_each进行遍历
//cout<<endl;
i=0;
j=1;
while(i<text.size()&&j<pattern.size())
{
if(j==0||text[i]==pattern[j])
{
++i;
++j;
}
else j=next[j];
}
if(j>n)
return i-n;
else return 0;
}
void main ()
{
/*char* who = "I"; `
char* whom = "优快云";
char s[32];
//char * s;字符串常量不能更改,所以存成数组
sprintf(s, "%s love %s.", who, whom);
cout<<s<<endl;
cout<<sizeof(s)<<endl;//32
cout<<strlen(s)<<endl;//12
char * str="abaabcac";
int n=strlen(str);
cout<<n<<endl;
char *strtemp=new char[n];
//当用char str[n];时不行
sprintf(strtemp,"%d%s",n,str);
string pattern=string(strtemp);
cout<<"pattern:"<<pattern<<endl;
*/
int *next=new int[9];
string pattern="1abaabcac";//数据结构书上第一个为串长,这里为1
string text="1acaccbabbabaabcac";
int out=find_substring(pattern,text);
cout<<out<<endl;
getchar();
}