1. BF Algorithm Introduction:
BF (Brute Force) algorithm is a common pattern matching algorithm, also known as the naïve matching algorithm or brute force algorithm, the biggest disadvantage of this algorithm is that the character matching failure pointer will backtrack, so the performance is very low.
2. BF algorithm thought:
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
The idea of the BF algorithm is to match the first character of the target string s with the first character of the pattern string T. If equal, continue to compare the second character of S and the second character of T, and if not equal, compare the second character of S and the first character of P, and then compare until the final match is reached.
3. Java implementation:
Naive matching algorithm public
class Bruteforce {
/**
* @param mainstr main string
* @param subStr substring
* @return string Match successful start position
*/public
static int Getmatchindex (string mainstr, String subStr) {
int i = 0, j = 0;
while (I < mainstr.length ()) {
if (Mainstr.charat (i) = = Substr.charat (j)) {//Two letters equal will continue to
i++;
j + +;
} else {///two letter unequal angle back start match
i = i-j + 1;//I Fall back to the next j = 0 of the last match first
;//J Back to substring first
}
if (j = = Substr.le Ngth ()) return
i-j;
return-1;
}
public static void Main (string[] args) {
System.out.println ("The location where the match was successful:" + Getmatchindex ("God is a Girl", "Girl"));
}
}
Note: In fact, the Java API has implemented a string matching algorithm, such as: "ABC". INDEXOF ("BC") will return 1. This is just a simulation of the algorithm, for reference only.
4. BF Algorithm Time Complexity:
At worst, the algorithm is compared with M * (n-m + 1), and the time complexity is O (M * N).
Author: csdn Blog zdp072