The/** * naive string algorithm looks for substrings through two loops, * as if a "template" containing a pattern slides along an identifying text.
* The idea of the algorithm is: from the main string s of the first POS word Fu Qi and pattern string comparison, * when the match is unsuccessful, from the main string s of the first pos+1 character back to the pattern string comparison.
* If the length of the main string s is N and the pattern string length is M, then the brute-force time complexity is O (m*n).
* The worst case occurs in a substring of a pattern string that appears frequently in the main string s.
* Although its time complexity is O (m*n), but in general the matching time is O (m+n), * So in practice it is used in large quantities.
* The advantage of this method is: the algorithm is simple and clear, easy to realize memory.
* The disadvantage of this method is that backtracking is not efficient, and these backtracking are not necessary.
* The following is the Java code for the algorithm, find the substring, return the substring in the parent string the first occurrence of the position, * can not find the words returned 0.
* * Package Al;
public class Bruteforce {public static void main (string[] args) {String Waitformatch = "Abbacbabcdabcbec";
String pattern = "ABCBE";
Bruteforce bruteforce = new Bruteforce ();
int index = Bruteforce.getsubstringindex (Waitformatch, pattern);
SYSTEM.OUT.PRINTLN ("Matched index is" +index); /** * @author * @param waitformatch Main String * @param pattern Mode String * @return First string match successful position/pub
Lic int Getsubstringindex (string waitformatch, string pattern) {int stringlength = Waitformatch.length (); int patternlength = Pattern.length (); Start comparison for (int i=0; i<stringlength; i++) {int k = i;//k to point to the next position of the main string for (int j=0; J<patternlen Gth
J + +) {if (Waitformatch.charat (k)!= Pattern.charat (j)) {break;
}else {k++;//points to the next position of the main string if (j = = patternLength-1) {return i;
}}}//Match unsuccessful, returns 0 return 0; }
}