1,若第i个开始不等,移动到第i个。
直接将sub[0]与src[5]比较。
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
a | b | c | a | b | a | b | c | a |
a | b | c | a | b | x |
2,
sub[2]与src[5]比较。
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
a | b | c | a | b | a | b | c | a |
a | b | c | a | b |
看大神的代码理解不了,还是按自己的思路写一个,繁琐还是起码好理解就行。
void getNext(const char * sub, int next[])
{
int i=1,compareIndex=0;
next[0]=-1;
next[1]=0;
bool bLastEquel=false;
while (sub[i+1]!='\0')
{
if(sub[i]==sub[compareIndex])
{
bLastEquel=true;
i++;
compareIndex++;
// original_next=compareIndex
if(sub[i]==sub[compareIndex]) //判断当前的sub[i]字符与originalNext对应sub字符是否相等
next[i]=next[compareIndex];
else
next[i]=compareIndex;
}
else
{
compareIndex=0;
if (bLastEquel==false)
{
i++;
if(sub[i]==sub[compareIndex])
next[i]=next[compareIndex];
else
next[i]=compareIndex;
}
bLastEquel=false;
}
}
}
int strstrForNext(const char *src,const char *sub)
{
assert(src!=nullptr&&sub!=nullptr);
const char* src2=src,*sub2=sub;
size_t index=0;
int *pNext = new int [strlen(src)];
get_nextval(sub,pNext);
size_t i=0,j=0;
while ( src2[i]=='\0' && sub2[j]=='\0' )
{
if (src2[i]==sub2[j])
{
i++;
j++;
}
else
{
index=index+j+1;
if(pNext[j]==-1)
{
i++;
j=0;
}
else
j=pNext[j];
}
}
delete []pNext;
if ( sub2[j]=='\0')
{
return index;
}
return -1;
}
int main()
{
char *p="aaaaaaaab";
char *q="yu";
int *nextRes=new int[strlen(p)+1];
getNext(p,nextRes);
for (int i=0;i<strlen(p)+1;i++)
{
cout<<nextRes[i]<<endl;
}
cout<<strstrForNext(p,q)<<endl;
}