First, the basic idea of BF algorithm
BF (Brute Force) algorithm is a pattern matching the simplest and most intuitive algorithm. The basic idea of the algorithm is to compare the first sequence from the start of the main character and pattern P (substring to be retrieved) in the first character, if equal, comparing the subsequent characters one by one; if it is found during the comparison is not equal to case, then back to the primary sequence of the first character position start + 1, and re-compares the character pattern P.
Second, the algorithm code
. 1 Package algorithm; 2 . 3 Import java.util.Scanner; . 4 . 5 / ** . 6 * string matching algorithms: the BF . 7 * / . 8 public class the BF { . 9 // main string 10 Private String S1; . 11 // target string 12 Private String S2; 13 is 14 / ** 15 * main console input string, the target string 16 * using { @link Scanner nextLine} # can receive the rest of the current line (non-end), and including spaces. 17 * Scanner is of course to use a method wherein the. 18 * / 19 public void Read () { 20 is // input main string 21 is System.out.println ( "Please enter the main string:" ); 22 is Scanner Scan = new new Scanner (the System.in); 23 is // input characters to be matched to give 24 the System .out.println ( "enter a destination string:" ); 25 Scanner AIM = new new Scanner (the System.in); 26 is IF (scan.hasNext ()) { 27 S1 = scan.nextLine (); 28 the System.out. println ( "main string as input:" + S1); 29 } 30 IF (aim.hasNext ()) { 31 is S2 = aim.nextLine (); 32 System.out.println ( "target string is entered:" + S2); 33 is } 34 is 35 IF (s1.length () < s2.length ()) { 36 the System. out.println ( "run length must be greater than the primary target string, please re-enter!" ); 37 [ Read (); 38 is } 39 40 // Close 41 is scan.close (); 42 is aim.close (); 43 is } 44 is 45 / ** 46 * string matching algorithm BF, arithmetic average time complexity is O ((nm) m), n mainly run length, m is the length of the target string. 47 * 48 * @Param start matched from the start position of the main string 49 * @return to true match succeeds, otherwise fails 50 * / 51 is public Boolean BF ( int start) { 52 is Read (); // input main string, the target string parameter 53 is int I, J; 54 is for (I = Start; I <s1.length () - s2.length ();) { 55 for (J = 0; J <s2.length (); J ++ ) { 56 is IF (S1. ! the charAt (I) = s2.charAt (J)) { 57 is I ++ ; 58 BREAK ; //A character re-start looking from the lower main string, just back 59 } the else { 60 I ++; // successful match, starts the next character comparison of two strings 61 } 62 // target string after the matching, the matching is successful will return results 63 is IF (s2.length J == () -. 1 ) { 64 return to true ; 65 } 66 } 67 } 68 return to false ; 69 } 70 71 is }
BF algorithm average time complexity of O ((nm) m), n mainly run length, m is the length of the target string. BF algorithm may frequently be back, work efficiency is not high.