The time complexity of the KMP algorithm is O (M + N), while the time complexity of the boyer-moore algorithm is O (n/m). In text lookup, "Ctrl + F" is generally used as the BM algorithm.
key points of the Boyer-moore algorithm:
from the right traversal, if there is a txt inside the i+j element and Pat inside the J element is inconsistent, adjusted. According to right[] adjustment, right[] similar to KMP algorithm inside the nextval. Skip = J-right[txt.charat (i+j)]; if (Skip < 1) skip = 1; I+=skip; That is, find the first I+J element in a txt where the rightmost position is in pat, and if so, two aligned. If it does not exist, move the I back directly to the i+j+1 position. The code is as follows:
classSolution { Public: BOOLSearchstringPatstringtxt) { //string matching problem, using BM algorithm//Calculate Jump Tables//----------------------------------------------- //2^8, a character that occupies only one byte, a total of 8 bits int* right =New int[SIZE]; //Initialize all values to-1 for(inti =0; i < SIZE; i++) {Right[i]= -1; } //The value contained in the PAT pattern string is the right value in which it appears for(inti =0; I < pat.size (); i++) {Right[pat[i]]=i; } //----------------------------------------------- //find string Pat in txt intN =txt.size (); intM =pat.size (); intSkip =0; for(inti =0; I <= n-m; i + =Skip) { //does the pattern string and text match in position I? //when a match fails, the character in the text is skipped by jumping and it is in the pattern string//The right-most-aligned position appearsSkip =0; for(intj = M-1; J >=0; j--){ if(Txt[i + j]! =Pat[j]) {Skip= J-right[txt[i +J]]; if(Skip <1) Skip =1; Break; } } if(Skip = =0) { Delete[] right; return true;//or return i; Find a match } } Delete[] right; return false;//no match found }Private: Const intSIZE = the;};
Boyer-moore (BM) algorithm, text lookup, string matching problem