(i) BF algorithm to understand
The BF algorithm, the Storm (Brute force) algorithm, is a common pattern matching algorithm.
The idea of BF algorithm is to match the first character of the target string s with the first character of the pattern string T, and if it is equal, continue to compare the second character of S with the second character of T;
If not equal, compare the second character of S with the first character of T, and then compare until the final matching result is reached. BF algorithm is a brute force algorithm.
(ii) algorithm simulation
Start matching:
First match: H and L are not equal, string s moves down one, string T goes back to its original position
Second match: L and O are unequal, the string s moves to the next position, and the string T returns to its original location.
Third match: L and L match up, record this position as a, string s moves to the next position, and the string T moves to the next position, continuing to match
Fourth match:L and E do not match, move the string s to the next position marked as a to re-match, and the string T back to its original location
Fifth matches:L and L are matched, the position is recorded as B, the string s moves to the next position, and the string T moves to the next position, continuing to match
Sixth matches:E and E match up, the string s moves to the next position, and the string T moves to the next position, continuing to match
Seventh matches:W and W match up, string T all match successfully, one match succeeds.
(c) Code implementation: Before we implement sequential storage string is the BF algorithm
intIndex (String S, String T,intPos//returns the position of the substring T after the POS character in the main string s, and returns 0 if it does not exist .{ intI, J; I= pos;//for the current position subscript in the main string s, and if POS is not 1 o'clock, the match starts at the POS positionj =1;//used for sub-string T multiple current position subscript value while(i<=s[0]-t[0]+1&&j<=t[0])//If the length of I is less than the matched length and j is less than the length of T, the loop { if(S[i]==t[j])//two characters typeface, etc. continue to match{J++; I++; } Else //Pointer rewind re-match{i= I-j +2;//Note that the plus 2,i of this index is returned to the next position in the last match firstj =1;//J Returns the first of the substring T } } if(J > t[0]) returni-t[0]; return 0;}
The BF algorithm is also the backtracking method
(iv) Performance analysis
s=000000000000000000000000000001T=0000001
The worst time complexity is O ((n-m+1) *m)
In the actual use, for the computer, processing is bits 0 and 1 of the string, a character can be regarded as 8 0/1 strings, Chinese characters and pictures more, so when we use BF matching efficiency is very low
Data structure (iii) string---BF algorithm (naïve pattern matching)