String search algorithm BM algorithm (Boyer-Moore) Algorithm

Source: Internet
Author: User

The two most famous character string search algorithms are KMP algorithm (knuth-Morris-Pratt) and BM algorithm (Boyer-Moore). In the worst case, both algorithms have linear search time. However, in practice, the KMP algorithm is not much faster than the simplest C-database function strstr (), while the BM algorithm is usually 3-5 times faster than the KMP algorithm.

However, in the worst case, the time complexity of BM seems to be n × n.

Not to mention the specifics. The BM algorithm uses the main text string to quickly perform non-backtracking search. The beating algorithm is implemented using this sentence in the program. below:

  1. I = I + M-min (J, 1 + last (P, T [I]);

Last is the final position of the character in the search string.

This algorithm is very troublesome. If you can, Baidu.

The Code is as follows:

  1. # Include <string. h>
  2. Int last (char * P, char c) {// locate the position where c finally matches in P. If no position is found,-1 is returned.
  3. Int length = strlen (P), Count = 0;
  4. Char * PP = P + Length-1;
  5. While (PP> = P)
  6. {
  7. If (* PP = C)
  8. {
  9. Return length-count-1;
  10. }
  11. PP --;
  12. Count ++;
  13. }
  14. Return-1;
  15. }
  16. Int min (int A, int B ){
  17. Return (A <= B )? A: B;
  18. }
  19. Int bm_index (char * t, char * P ){
  20. Int n = strlen (t );
  21. Int M = strlen (P );
  22. Int I = s-1, j = m-1;
  23. While (I <= N-1)
  24. {
  25. If (T [I] = P [J])
  26. {
  27. If (j = 0)
  28. {
  29. Return I;
  30. }
  31. Else
  32. I --, j --;
  33. }
  34. Else {
  35. I = I + M-min (J, 1 + last (P, T [I]); // jump back, depending on the position of the last matched character
  36. J = m-1;
  37. }
  38. }
  39. Return-1;
  40. }
  41. Int _ tmain (INT argc, _ tchar * argv [])
  42. {
  43. Char * P = "woainizz! Izzzzzz -- zzzzzzut ";
  44. Int A = bm_index (P, "zzzzut"); // result 18, no problem
  45. Return 0;
  46. }

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.