Pattern matching
In the string matching problem, we expect to see if the source string "s string" contains the target string "string T" (also known as the pattern string). Where string s is called the main string, the string T is called a substring.
1. If a substring is found in the main string, then the pattern match is successful, and the first character of the pattern string is returned where it appears in the main string.
2. If the substring is not found in the main string, then the pattern match fails and returns-1.
There are two classical algorithms in the pattern matching process: The Brute-force and KMP algorithms are two of the most classical pattern matching algorithms.
In this film, the main analysis of BF algorithm, very yellow very violent. The following is a simple thought analysis:
1. The basic idea is : Start with the first character of the target string s= "S0s1...sn-1" and the first character in the pattern string t= "t0t1...tm-1", and if equal, continue to compare the subsequent characters one by one, otherwise, Starting from the 2nd character of the target string s to be compared with the first character of the pattern string T, and so on, if starting from the second character of the target string s, each character is equal to the corresponding character in the pattern string T, then the matching succeeds, the algorithm returns I; otherwise the match fails, returns 1.
2. Give a chestnut:
Set the main string s= "CDDCDC", pattern string t= "CDC", Pattern matching process
//================================
1 //pattern matching algorithm of string, BF algorithm2 Public classBruteforce {3 //4 /**5 * 6 * @paramsrc7 * Main string8 * @paramSub9 * String (pattern string)Ten * The algorithm is relatively simple, the disadvantage is that every time the retrospective efficiency is not high, backtracking is often not necessary One */ A Public Static intbrutefore (String src, string sub) { - inti = 0, j = 0; - intindex =-1; the while(I < Src.length () && J <sub.length ()) { - if(Src.charat (i) = =Sub.charat (j)) { -i++; -J + +; +}Else { - /** + * Here's an understanding of the formula: The objective of this equation is to ensure that the value of I is continuously backwards when the match is unsuccessful +1 J actually indicates the number of characters that have been successfully matched. A * I is a continuous process of accumulation at */ -i = i-j + 1; -j = 0; - } - } - //Judging in if(J = =sub.length ()) { - //This means that the match is started at index and the following exact match succeeds toindex = i-sub.length (); + } - the returnindex; * } $}
The algorithm corresponds to the above illustrated example and can be read and understood by itself.
Down-turn KMP algorithm
A string pattern matching algorithm---brute-force algorithm of Java data structure