Java implementation of string search algorithm Boyer-moore

Source: Internet
Author: User

Because it is the reason for career change after graduation, so I do not have a systematic study of data structure, algorithm introduction and other classes before the work. Plainly, there is no such a foundation, haha. So this blog is mainly for themselves to see, because time is limited, I write the content estimates far will not have everyone expect so detailed, so, can this article can choose to ignore OH.

Algorithm Introduction: about the Boyer-moore algorithm (hereinafter referred to as BM algorithm) concept on-line search a lot. So this is not a concrete elaboration. In doubt, refer to this article of Nanyi (this writing is delicate and easy to understand):

Nanyi: Boyer-moore algorithm for string matching

The essence of the algorithm: This string lookup algorithm is efficient because it can skip multiple characters at a time when the string does not match exactly. It does not require a comparison of the characters in the string being searched. So, how do you skip it? Of course, the use of the pattern string (pattern) and the literal (text) in the matching process of the known information to skip some unnecessary comparisons. The two heuristic strategies recommended above for blog post's bad character algorithm (bad-character) and good suffix algorithm (good-suffix) are used to decide how to move (shift) or how many bits to move, not here.

Complete algorithm: because this article is mainly used to help remember, not to tell you how to implement the algorithm. So I put out the complete code (Java implementation), and then do a further code analysis it.

 Public  class boyermoore{     Public Static void Main(string[] args) {String Text ="Here's a simple example"; String pattern ="Example"; Boyermoore BM =NewBoyermoore ();    Bm.boyermoore (pattern, text); } Public void Boyermoore(string pattern, string text) {intm = Pattern.length ();intn = text.length (); map<string, integer> BMBC =NewHashmap<string, integer> ();int[] Bmgs =New int[M];//ProprocessingPREBMBC (Pattern, M, BMBC); Prebmgs (Pattern, M, Bmgs);//Searching        intj =0;inti =0;intCount =0; while(J <= N-m) { for(i = m-1; I >=0&& Pattern.charat (i) = = Text.charat (i + j); i--) {//For countingcount++; }if(I <0) {System.out.println ("One position is:", M); J + = bmgs[0]; }Else{J + = Math.max (Bmgs[i], GETBMBC (string.valueof (Text.charat (i + j)), BMBC, M)-M +1+ i); }} System.out.println ("Count:"+ count); }Private void PREBMBC(String pattern,intPatlength, map<string, integer> bmbc) {System.out.println ("BMBC Start process ..."); { for(inti = patlength-2; I >=0; i--)if(!bmbc.containskey (string.valueof (Pattern.charat (i))) {Bmbc.put (string.valueof (Pattern.charat (i)), (Integer) (Patlength-i-1)); }        }    }Private void Prebmgs(String pattern,intPatlength,int[] bmgs) {intI, J;int[] suffix =New int[Patlength]; Suffix (pattern, patlength, suffix);no substring in the pattern string matches the suffix, and a maximum prefix is not found         for(i =0; i < patlength;        i++) {Bmgs[i] = patlength; }no substring in the pattern string matches the good suffix, but a maximum prefix is foundj =0; for(i = patlength-1; I >=0; i--) {if(Suffix[i] = = i +1)            { for(; J < patlength-1I J + +) {if(Bmgs[j] = = patlength) {Bmgs[j] = patlength-1I }                }            }        }//pattern string with substring matching good suffix         for(i =0; I < patlength-1; i++) {bmgs[patlength-1-Suffix[i]] = patlength-1I } System.out.print ("Bmgs:"); for(i =0; i < patlength; i++) {System.out.print (Bmgs[i] +",");    } System.out.println (); }Private void suffix(String pattern,intPatlength,int[] suffix) {suffix[patlength-1] = Patlength;intQ =0; for(inti = patlength-2; I >=0; i--) {q = i; while(Q >=0&& Pattern.charat (q) = = Pattern.charat (Patlength-1-i + q)) {q--;        } Suffix[i] = I-q; }    }Private int GETBMBC(String C, map<string, integer> BMBC,intm) {//Returns the length of pattern if the corresponding value is returned in the rule        if(Bmbc.containskey (c)) {returnBmbc.get (c); }Else{returnM }    }}

algorithm theory Discussion and code analysis:
A1: A discussion on the theory of bad character arithmetic
When a bad character occurs, the BM algorithm moves the pattern string to the right, making the right-most corresponding character in the pattern string relative to the bad character, and then continues to match. There are two cases of bad character arithmetic.

1. When there is a corresponding bad character in the pattern string, the corresponding character in the pattern string is relative to the bad character (because it is the right character in the pattern string, it is possible for the pattern string to move left, or there may be backtracking, but if we go back, the moving distance is negative, Must not be the maximum number of moving steps).

2. There is no bad character in the pattern string, very good, just right move the whole pattern string length so big stride number.

A2: Bad character algorithm specific steps to perform:
When the BM algorithm substring is compared mismatch, the distance that the pattern needs to move right is calculated by the bad character algorithm, and the BMBC array is used to calculate the distance of the right shift of the pattern by the good suffix algorithm. Bmgs array. Here's how to calculate the BMBC array.

Bmbc[] Array, a character index, such as bmbc[' V '), indicates the length of the last occurrence of the character V in the pattern string, distance from the end of the pattern string.

Computes the bad character array bmbc[]:
This calculation should be easy, it seems that only need bmbc[i] = m–1–i on the line, but this is not right, because the character at the I position may appear in the pattern in many places (as shown), and we need to be the rightmost position, so that each cycle must be judged, very cumbersome, poor performance. The trick here is to use a character as a subscript instead of a positional number as the subscript. This only needs to be traversed once, which seems to be a space-time approach, but if it is a pure 8-bit character also requires only 256 space size, and for large mode, it may be more than 256 of the length, so it is worthwhile (this is why the larger the data, the more efficient BM algorithm is one of the reasons).

As mentioned earlier, the calculation of bmbc[] is divided into two cases, corresponding to the first one by one.
Case1: The character appears in the pattern string, bmbc[' V '] represents the last occurrence of the character V in the pattern string, the distance pattern string
The length of the tail, as shown in.
Case2: The character does not appear in the pattern string, if there is no character V in the pattern string, then bmbc[' V ' = strlen (pattern).

It's also easy to write Case1 as pseudo-code:

void PreBmBc(charintint bmBc[]){    int i;    for0256; i++)    {        bmBc[i] = m;    }    for01; i++)    {        1 - i;    }}

Of course, in the complete code I put out to use map as the storage structure of BMBC, so Case1 Java expression is as follows:

Private voidPREBMBC (Stringpattern, int patlength,Map<String,Integer>BMBC) {System.Out.println"BMBC Start process ..."); {for (int i=Patlength- 2; I>= 0; I--)if(!Bmbc.ContainsKey (String.ValueOf (Pattern.CharAt (i)))) {BMBC.PutString.ValueOf (Pattern.CharAt (i)), (Integer) (Patlength-I- 1)); }        }    }

So, how to express Case2, incredibly simple, see below: The use of map as a BMBC storage container in the case of text characters can not be exhausted 256 more space-saving:

privateintgetBmBcint m)    {        // 如果在规则中则返回相应的值,否则返回pattern的长度, 参数m恒等于pattern的长度        if (bmBc.containsKey(c))        {            return bmBc.get(c);        }        else        {            return m;        }    }

B1: A good suffix algorithm theory discussion
If the program matches a good suffix, and there is another part of the same suffix or suffix in the pattern, move the next suffix or section to the current suffix position. If you say that the last U character and text of the pattern match, but the next character does not match, I need to move to match. If the after U character appears elsewhere in the pattern or part of it, we move the pattern right to the front U character or part and the last U character or part is the same, if the after U character does not appear in the other position of the pattern at all, it is good to move the pattern directly to the right. In this way, a good suffix algorithm has three scenarios:

1. The substring in the pattern string matches the good suffix exactly, then the right-most substring is moved to a good suffix to continue the match.

2. If there are no substrings that match the good suffix exactly, find the oldest string with the following characteristics in the good suffix, making p[m-s...m]=p[0...s].

3. If there is no substring matching the good suffix at all, move the entire pattern string to the right.

In conclusion, the moving rule of the complete BM algorithm is that the movement step of each comparison of the pattern string is max (Shift (good suffix), shift (bad character)), that is, the BM algorithm is the distance to move the pattern string to the right, according to the good suffix algorithm and the bad character algorithm to calculate the maximum value. The preprocessing array of the bad character algorithm is bmbc[], and the preprocessing array of the good suffix algorithm is bmgs[].

B2: Good suffix algorithm specific execution steps:
The subscript for bmgs[] here is a number instead of a character, which indicates the position of the character in pattern. As mentioned earlier, the Bmgs array is calculated in three different cases, corresponding to the first one by one. Suppose the good suffix length in the figure is expressed in array suff[].
Case1: corresponds to a good suffix algorithm case1, for example, K is the position before the good suffix.

Case2: Corresponds to a good suffix algorithm case2: as shown:

Case3: Corresponding and good suffix algorithm case3,bmgs[i] = strlen (pattern) = M

According to the illustration above, the code given is as follows:

Private void Prebmgs(String pattern,intPatlength,int[] bmgs) {intI, J;int[] suffix =New int[Patlength]; Suffix (pattern, patlength, suffix);all assignments are M, including Case3         for(i =0; i < patlength;        i++) {Bmgs[i] = patlength; }//Case2j =0; for(i = patlength-1; I >=0; i--) {if(Suffix[i] = = i +1)            { for(; J < patlength-1I J + +) {if(Bmgs[j] = = patlength) {Bmgs[j] = patlength-1I }                }            }        }the longest good suffix in the pattern string is Case1         for(i =0; I < patlength-1; i++) {bmgs[patlength-1-Suffix[i]] = patlength-1I } System.out.print ("Bmgs:"); for(i =0; i < patlength; i++) {System.out.print (Bmgs[i] +",");    } System.out.println (); }

The above code uses the suffix array, how do you ask for this array? In fact Suffix[i] is the length of the common suffix string with the I-position word identifier suffix and the last word identifier suffix in the pattern. So, its implementation is as follows:

private  void  suffix  (String pattern, int  patlength, int  [] suffix) {suffix[patlength-1 ] = patlength;        int  q = 0 ; for  (int  i = patlength-2 ; I >= 0 ;         i--) {q = i; while  (q >= 0  && pattern.charat (q) = = Pattern.charat (patlength-1 -i + q)" {q--;            } Suffix[i] = I-q; }    }

At this point, the key code of the BM algorithm is basically finished. The complete code is also given at the very beginning. Here, I would like to say that the code given here there are many things that can be optimized and improved, interested readers, can refer to this blog post (in C # implementation) OH:

grep's String search algorithm Boyer-moore-to-digest (3-5 times faster than KMP)

Java implementation of string search algorithm Boyer-moore

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.