next array solving (Code) KMP Algorithms

EDITORIAL

408 exam study period of time to see the first video bilibili accompanied by:
Links: Link
to this video primarily for examinations, did not say the idea of code, here I am Along the way video, write code, if they are not thinking clearly place, Wang pointed out, and you can look at this video.

Thinking

As an example:
Here Insert Picture Description
observation we can know first find maxL, maxL is the end of the current character string matching.

Calculation method:

First default is 0, and if a second one is the same, different from 0 (where b is 0 and therefore a different).
Subsequent sequences, since the string may be calculated :( from zero by default, so the above number is 0 from the start code rather than starting from 1) in the following manner
due to some previous character is the end of the previous character to match string, so if the current character may be a character matching the character in front of one and the same, the maxL [i] = maxL [i -1] +1; is obtained on a number of arrays next +1.
If not, it depends on the current character and the first character of the same is not the same, the same as at the beginning of the current character string, that is, 1, or 0 if different;

If the above can not read directly look at an example:

As a number of 4, it is in front of his position 3 a, maxL [3] = 1 , the next number to find a number of two, is b, a and b are different due. It is determined and the beginning of a string are the same, because it is the same one.
After seeking out maxL, adding -1 left, pan right then one by +1 (since the beginning of the originally 0, so next [0] = maxL [0 ] and need not move) the remaining solution of a cycle:

for(int i =s.length()-1;i>0;i--){
		next[i]=next[i-1]+1;
	}

Code

Of course, if you think I write the code thief ugly, their own change to change just fine

#include<stdio.h>
#include<string>
#include<iostream>
using namespace std;
int next[100];
void getnext(string s){
	next[0]=0;
	for(int i =1;i<s.length();i++){
		if(i==1){
			if (s[1]==s[0]) next[1]=1;
			else next[1]=0;
		}
		if(s[i]==s[next[i-1]]) next[i]=next[i-1]+1;
		else if (s[i]==s[0]) {
			next[i]=1;
		}
		else{
			next[i]=0;
		} 
	}
	for(int i =s.length()-1;i>0;i--){
		next[i]=next[i-1]+1;
	}
}
int main(){
	string s;
	cin>>s;
	getnext(s);
	for(int i =0;i<s.length();i++)
	printf("%d ",next[i]);
	
}

Operating results map

Examples of the video:
Here Insert Picture Description
kingly title data structure kmp 6:
Here Insert Picture Description
are correct

Published 12 original articles · won praise 3 · Views 1285

Guess you like

Origin blog.csdn.net/github_38201918/article/details/104080943