String Matching brute force algorithm and string matching KMP Algorithm
Statement: Let's take a look at the network logs of Ruan Yifeng to explain the KMP algorithm of strings. All the images in this article are referenced in this log.
In the previous written test, I encountered a problem about string matching. I didn't write a good algorithm for the first time. Analysis now
Brute force algorithm and KMP AlgorithmPrinciples, AndCode Implementation,DifferencesAnd summarizeGeneral idea of good Algorithms.
========================================================== ==========================================
Principles:
Brute force algorithms:
1.
We name the long string as a text string strText, and the short string as the target string and strTarget.
The first character 'B' of the "BBC ABCDAB abcdababde" and the first character 'a' of the target string "ABCDABD'
The comparison does not produce matching. In the whole process, we assume that the red dotted line is fixed. Therefore, the text string moves one character to the left.
2.
The character 'B' and 'A' do not match, and the text string is moved left.
3.
Until now, the first match is displayed. The program moves the text string and the target string to the left and records the text string for comparison.
The position of the element (that is, the character 'a.
4.
Continue the comparison. It is a match and continues to move.
5.
In this case, the match does not exist, and the comparison is reset. The next character 'B' is entered Based on the 'A' position text string recorded earlier, and the subscript of the target string starts again,
Continue the comparison.
6.
This is the general principle analysis process of the brute-force algorithm.
Code implementation:
voidSViolence( const char strText[ ], const char strSearch[ ] ){ int lengthOfstrText, lengthOfstrSearch; int i, j, ii; lengthOfstrText = strlen( strText ); lengthOfstrSearch = strlen( strSearch ); /*for( i = 0, j = 0, ii = 0; i < lengthOfstrText && j < lengthOfstrSearch; )*/ for( i = 0, j = 0, ii = 0; j < lengthOfstrSearch; ) { if( strText[ i ] == strSearch[ j ] ) { j++; i++; continue; } else { i = ii; i++; ii = i; j = 0;/* make a clear */ continue; } } if( j == lengthOfstrSearch ) printf( "Existence!" ); else printf( "No Existence!" );}
The ii variable in the program records the location. Understanding the running process of this algorithm clearly shows that many repeated comparisons have been made in the algorithm.
Time Complexity Analysis: At first glance, this program feels very fast (man). There is only one for loop. Well, you don't know. This for loop is different. Its end is not only dependent on the for loop condition, but on the I, j, ii, and other variables. We remember that lengthOfText = m and lengthOfSearch = n; so the time complexity of this algorithm is probably T (n) = O (m * n), which we have put aside.