Horspool 字符串匹配算法


Horspool 字符串匹配算法對Boyer-Moore算法的簡化算法。

Horspool 算法是一種基於后綴匹配的方法,是一種“跳躍式”匹配算法,具有sub-linear亞線性時間復雜度

Horspool 算法:

  對於每個搜索窗口,該算法將窗口內的最后一個字符模式串中的最后一個字符進行比較。如果相等,則需要進行一個校驗過程。該校驗過程在搜索窗口中從后向前對文本和模式串進行比較,直到完全相等或者在某個字符處不匹配。無論匹配與否,都將根據字符d在模式串中的下一個出現位置將窗口向右移動

   可以使用下圖進行理解:

  (1)窗口大小與模式串大小相同,窗口內容為文本內容的一部分。

  (2)對於窗口而言,每次從后向前匹配,直到全部相等(匹配),或者遇到不相等。

  (3)遇到不相等時,根據窗口中最后一個字符在模式串中的位置,窗口進行移動。如果模式串中有多個相同的字符,選擇最后一個字符為准,以避免漏解。

  

代碼(C++):

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 /**
 5 計算可跳轉字符個數數組
 6 */
 7 int getDis(string &str,int *dis)
 8 {
 9     int len=str.length();
10     for (int i = 0; i < 256; i++)
11         dis[i]=len;    //最大跳躍字符數
12 
13     for (int i = 0; i < len-1; i++)    //注意這里不包括最后一個
14         dis[str[i]]=len-1-i;
15     return 0;
16 }
17 
18 /**
19 查找
20 */
21 int search(string &text,string &pattern,int *dis)
22 {
23     int j,pos;
24     bool tag=false;
25     int lenPattern=pattern.length();
26     int lenTrext=text.length();
27 
28     j=0;
29     pos=0;
30     while(pos<=lenTrext-lenPattern)
31     {
32         j=lenPattern-1;
33         while(j>=0 && pattern[j]==text[pos+j])  //向前搜索
34             j--;
35         if(j==-1)
36         {
37             tag=true;
38             cout<<"The result is :"<<pos<<endl<<endl;
39             pos=pos+lenPattern;
40             continue;
41         }
42         else
43             pos=pos+dis[text[pos+lenPattern-1]];    //使用最后一個字符對齊的方法,進行“跳躍”移動
44     }
45     if(tag == false)    //不存在匹配
46         cout<<"-1"<<endl<<endl;
47     return 0;
48 }
49 
50 int main()
51 {
52     int dis[256];
53     string text;
54     string pattern;
55     while(true)
56     {
57         cout<<"文本:";
58         cin>>text;
59         cout<<"模式:";
60         cin>>pattern;
61         getDis(pattern,dis);
62         search(text,pattern,dis);
63     }
64     return 0;
65 }
View Code

 程序運行:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM