字符串匹配常用算法

  字符串匹配(string match)是在實際工程中經常會碰到的問題,通常其輸入是原字符串(String)和子串(又稱模式,Pattern)組成,輸出爲子串在原字符串中的首次出現的位置。通常精確的字符串搜索算法包括暴力搜索(Brute force),KMP, BM(Boyer Moore), sunday, robin-karp 以及 bitap。下面分析這幾種方法並給出其實現。假設原字符串長度M,字串長度爲N。

1. Brute force.

該方法又稱暴力搜索,也是最容易想到的方法。

預處理時間 O(0)

匹配時間複雜度O(N*M)

主要過程:從原字符串開始搜索,若出現不能匹配,則從原搜索位置+1繼續。

  1. /*  
  2.  * ===  FUNCTION  ====================================================================== 
  3.  *         Name:  bf 
  4.  *  Description: brute-force method for string match problem. 
  5.  * ===================================================================================== 
  6.  */  
  7. int bf(const char *text, const char *find)  
  8. {  
  9.     if (text == '/0' || find == '/0')  
  10.         return -1;  
  11.     int find_len = strlen(find);  
  12.     int text_len = strlen(text);  
  13.     if (text_len < find_len)  
  14.         return -1;  
  15.     char *s = text;  
  16.     char *p = s;  
  17.     char *q = find;  
  18.     while (*p != '/0')  
  19.     {  
  20.         if (*p == *q)  
  21.         {  
  22.             p++;  
  23.             q++;  
  24.         }  
  25.         else  
  26.         {  
  27.             s++;  
  28.             p = s;  
  29.             q = find;  
  30.         }  
  31.         if (*q == '/0')  
  32.         {  
  33.             return (p - text) - (q - find);  
  34.         }  
  35.     }  
  36.     return -1;  
  37. }  
 

 

2,KMP.

KMP是經典的字符串匹配算法。

預處理時間:O(M)

匹配時間複雜度:O(N)

主要過程:通過對字串進行預處理,當發現不能匹配時,可以不進行回溯。

  1. /*  
  2.  * ===  FUNCTION  ====================================================================== 
  3.  *         Name:  kmp 
  4.  *  Description:  kmp method for string match. 
  5.  * ===================================================================================== 
  6.  */  
  7. /* 
  8.  * examples of prepocessing for pattern 
  9.  * pattern_1:  
  10.  * a b c a b c a 
  11.  * 0 0 0 0 1 2 3 
  12.  * pattern_2: 
  13.  * a a a a b a a 
  14.  * 0 0 0 0 0 0 1 
  15.  */  
  16. int kmp(const char *text, const char *find)  
  17. {  
  18.     if (text == '/0' || find == '/0')  
  19.         return -1;  
  20.     int find_len = strlen(find);  
  21.     int text_len = strlen(text);  
  22.     if (text_len < find_len)  
  23.         return -1;  
  24.     int map[find_len];  
  25.     memset(map, 0, find_len*sizeof(int));  
  26.     //initial the kmp base array: map  
  27.     map[0] = 0;  
  28.     map[1] = 0;  
  29.     int i = 2;  
  30.     int j = 0;  
  31.     for (i=2; i<find_len; i++)  
  32.     {  
  33.         while (1)  
  34.         {  
  35.             if (find[i-1] == find[j])  
  36.             {  
  37.                 j++;  
  38.                 if (find[i] == find[j])  
  39.                 {  
  40.                     map[i] = map[j];  
  41.                 }  
  42.                 else  
  43.                 {  
  44.                     map[i] = j;  
  45.                 }  
  46.                 break;  
  47.             }  
  48.             else  
  49.             {  
  50.                 if (j == 0)  
  51.                 {  
  52.                     map[i] = 0;  
  53.                     break;  
  54.                 }  
  55.                 j = map[j];  
  56.             }  
  57.         }  
  58.     }  
  59.     i = 0;  
  60.     j = 0;  
  61.     for (i=0; i<text_len;)  
  62.     {  
  63.         if (text[i] == find[j])  
  64.         {  
  65.             i++;  
  66.             j++;  
  67.         }  
  68.         else  
  69.         {  
  70.             j = map[j];  
  71.             if (j == 0)  
  72.                 i++;  
  73.         }  
  74.         if (j == (find_len))  
  75.             return i-j;  
  76.     }  
  77.     return -1;  
  78. }  
 

注意:在預處理中,表面看起來時間複雜度爲O(N^2),但是爲什麼是線性的,在時間複雜度分析中中,通過觀察變量的變化來統計零碎的、執行次數不規則的情況,這種方法叫做攤還分析。我們從上述程序的j 值入手。每一次執行上述循環預處理語句中的第二個else時都會使j減小(但不能減成負的),而另外的改變j值的地方只有一處。每次執行了這一處,j都只能加1;因此,整個過程中j最多加了M-1個1。於是,j最多隻有M-1次減小的機會(j值減小的次數當然不能超過M-1,因爲j永遠是非負整數)。這告訴我們,while循環總共最多執行了M-1次。按照攤還分析的說法,平攤到每次for循環中後,一次for循環的複雜度爲O(1)。整個過程顯然是O(M)的。另外關於KMP的詳細分析,可以參考Matrix67KMP算法詳解

 

3,Boyer Moore

Boyer Moore是字符串匹配算法中的經典,可以參考論文a faster string searching algorithm。

預處理時間O(N + M^2)

匹配時間複雜度O(N)

主要過程:通過預處理原字符串以及待匹配字串,從而在匹配失敗時可以跳過更多的字符。

  1. /*  
  2.  * ===  FUNCTION  ====================================================================== 
  3.  *         Name:  bm 
  4.  *         Descritexttion:  Boyer–Moore method for string match. 
  5.  *====================================================================================== 
  6.  */  
  7. int bm(const char *text, const char *find)  
  8. {  
  9.     if (text == '/0' || find == '/0')  
  10.         return -1;  
  11.     int i, j, k;  
  12.     int text_len = strlen(text);  
  13.     int find_len = strlen(find);  
  14.     if (text_len < find_len)  
  15.         return -1;  
  16.     int delta_1[CHAR_MAX];  
  17.     for (i=0; i<CHAR_MAX; i++)  
  18.         delta_1[i] = find_len;  
  19.     for (i=0; i<find_len; i++)  
  20.         delta_1[find[i]] = find_len - i - 1;  
  21.     int rpr[find_len];  
  22.     rpr[find_len-1] = find_len - 1;  
  23.     for (i=find_len-2; i>=0; i--)  
  24.     {  
  25.         int len = (find_len - 1) - i;  
  26.         //find the reoccurence of the right most (len) chars  
  27.         for (j=find_len-2; j>=(len-1); j--)  
  28.         {  
  29.             if (strncmp(find+i+1, find+j-len+1, len) == 0)  
  30.             {  
  31.                 if ((j-len) == -1 || find[i] != find[j-len])  
  32.                 {  
  33.                     rpr[i] = j - len + 1;  
  34.                     break;  
  35.                 }  
  36.             }  
  37.         }  
  38.         //if the right most (len) chars not completely occur, we find the right  
  39.         //substring of (len). every step, we try to find the right most (len-k)  
  40.         //chars.  
  41.         for (k=1; j<(len-1) && k<len; k++)  
  42.         {  
  43.             if (strncmp(find+i+k, find, len-k) == 0)  
  44.             {  
  45.                 rpr[i] = 0 - k;  
  46.                 break;  
  47.             }  
  48.         }  
  49.         if (j<(len-1) && k == len)  
  50.         {  
  51.             rpr[i] = 0 - len;  
  52.         }  
  53.     }  
  54.     int delta_2[find_len];  
  55.     for (i=0; i<find_len; i++)  
  56.         delta_2[i] = find_len - rpr[i];  
  57.     i = find_len - 1;  
  58.     j = find_len - 1;  
  59.     while (i < text_len)  
  60.     {  
  61.         if (text[i] == find[j])  
  62.         {  
  63.             i--;  
  64.             j--;  
  65.         }  
  66.         else  
  67.         {  
  68.             if (delta_1[text[i]] > delta_2[j])  
  69.             {  
  70.                 i += delta_1[text[i]];  
  71.             }  
  72.             else  
  73.             {  
  74.                 i += delta_2[j];  
  75.             }  
  76.             j = find_len - 1;  
  77.         }  
  78.         if (j == -1)  
  79.             return i+1;  
  80.     }  
  81.       
  82.     return -1;  
  83. }  
 

提示:該算法主要利用壞字符規則和好後綴規則進行轉換。所謂壞字符規則,是指不能匹配時的字符在待匹配字串中從右邊數的位置;而好後綴規則則是指子串中從該不匹配位置後面所有字符(都是已匹配字符)再次在字串中出現的位置(k),其中s[k,k+1,---,k+len-j-1] = s[j+1, j+1,---,len-1], 並且s[k-1] !=  [j] || s[k-1] = $, 其中$表示增補的字符,可以與任何字符相等。

舉例來說,對於字串ABCXXXABC

   -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9

A B C X X X A B C

j=9 9//NULL->其值爲當前位置。

j=8 $ 0     //C->雖然出現在3,但[2] = [j],所以不滿足

j=7 $ $ -1    //BC出現在開始[2],但[1]=[j]

j=6 1    //ABC

j=5 $ 0    //XABC

j=4 $ $ -1    //XXABC

j=3 $ $ $ -2  //XXXABC

j=2 $ $ $ $ -3  //CXXXABC

j=1 $ $ $ $ $ -4   //BCXXXABC

 

4, Sunday

Sunday算法比較簡單,其實就是利用Boyer Moore中的壞字符規則,實現起來簡單,效果也還不錯。

預處理時間O(M)

匹配時間複雜度O(N*M)

  1. /*  
  2.  * ===  FUNCTION  ====================================================================== 
  3.  *         Name:  sunday 
  4.  *  Description:  sunday method for string match. 
  5.  * ===================================================================================== 
  6.  */  
  7. int sunday(const char *text, const char *find)  
  8. {  
  9.     if (text == '/0' || find == '/0')  
  10.         return -1;  
  11.     char map[CHAR_MAX];  
  12.     int i;  
  13.     int text_len = strlen(text);  
  14.     int find_len = strlen(find);  
  15.     if (text_len < find_len)  
  16.         return -1;  
  17.     //preprocess  
  18.     for (i=0; i<CHAR_MAX; i++)  
  19.         map[i] = find_len + 1;  
  20.     for (i=0; i<find_len; i++)  
  21.         map[find[i]] = find_len - i;  
  22.     //match process  
  23.     i = 0;  
  24.     while (i <= (text_len - find_len))  
  25.     {  
  26.         if (strncmp(find, text + i, find_len) == 0)  
  27.             return i;  
  28.         else  
  29.             i += map[text[i + find_len]];  
  30.     }  
  31.     return -1;  
  32. }  
 

 

5, Robin-Karp

Robin-Karp主要利用HASH函數來處理字串,從而完成匹配。

預處理時間O(0)

最壞匹配時間複雜度O(N*M)

  1. /*  
  2.  * ===  FUNCTION  ====================================================================== 
  3.  *         Name:  robin_karp 
  4.  *  Description:  robin_karp method for string match problem. 
  5.  * ===================================================================================== 
  6.  */  
  7. // karp_robin need a hash function  
  8. int hash(const char *s, unsigned int len)  
  9. {  
  10.     int result = 0;  
  11.     int base = 3;  
  12.     int i;  
  13.       
  14.     for (i=0; i<len; i++)  
  15.     {  
  16.         result += s[i];  
  17.         result *= base;  
  18.     }  
  19.     result /= base;  
  20.     return result;  
  21. }  
  22. int robin_karp(const char *text, const char *find)  
  23. {  
  24.     if (text == '/0' || find == '/0')  
  25.         return -1;  
  26.     int i, j;  
  27.     int text_len = strlen(text);  
  28.     int find_len = strlen(find);  
  29.     if (text_len < find_len)  
  30.         return -1;  
  31.     int h_find = hash(find, find_len);  
  32.     int h_tmp = 0;  
  33.     for (i=0; i<=(text_len-find_len); i++)  
  34.     {  
  35.         h_tmp = hash(text+i, find_len);  
  36.         if (h_tmp == h_find)  
  37.         {  
  38.             for (j=0; j<find_len; j++)  
  39.             {  
  40.                 if (find[j] != text[i+j])  
  41.                 {  
  42.                     break;  
  43.                 }  
  44.             }  
  45.             if (j == find_len)  
  46.                 return i;  
  47.         }  
  48.     }  
  49.     return -1;  
  50. }  
 

注意:主要依賴於hash函數的設計。

 

6, Bitap

Bitap算法主要利用位運算進行字符串的匹配,其匹配過程可以看作是有窮自動機中狀態的轉換,按照字串(pattern)的連續分解狀態進行轉換,從而到達終點,此時匹配過程完成。

預處理時間O(M)

最壞匹配時間複雜度O(N*M)

  1. /*  
  2.  * ===  FUNCTION  ====================================================================== 
  3.  *         Name:  bitap  
  4.  *         Description:  bitap method. 
  5.  *======================================================================================= 
  6.  */  
  7. int bitap(const char *text, const char *find)  
  8. {  
  9.     if (text == '/0' || find == '/0')  
  10.         return -1;  
  11.     int text_len = strlen(text);  
  12.     int find_len = strlen(find);  
  13.     if (text_len < find_len)  
  14.         return -1;  
  15.     int i = 0;  
  16.     int j = find_len - 1;  
  17.     char map[find_len + 1];  
  18.     map[0] = 1;  
  19.     for (i=1; i<=find_len; i++)  
  20.     {  
  21.         map[i] = 0;  
  22.     }  
  23.     for (i=0; i< text_len; i++)  
  24.     {  
  25.         for (j=find_len-1; j>=0; j--)  
  26.         {  
  27.             map[j+1] = map[j] & (text[i] == find[j]);  
  28.         }  
  29.         if (map[find_len] == 1)  
  30.         {  
  31.             return i - find_len + 1;  
  32.         }  
  33.     }  
  34.     return -1;  
  35. }  
 

注意:Bitap匹配算法中可以改用位移操作實現,從而將匹配複雜度從O(N*M)降低到O(N)。

 

總結,以上算法中,性能較好的爲KMP,BM, 實現簡單的爲BF,Sunday,Bitap。兩者折中來看,KMP表現較好。

預處理時間 匹配時間複雜度

BF O(0) O(N*M)

KMP O(M) O(N)

BM O(N+M^2) O(N)

Sunday O(M) O(N*M)

Robin-Karp O(0) O(N*M)

Bitap O(M) O(N*M)->O(N)

 

以上六種算法比較實現的代碼如下所示(其中string長度10000)。


轉自:http://blog.csdn.net/meixr/article/details/6456896

發佈了22 篇原創文章 · 獲贊 13 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章