標籤:style blog http color io os ar strong for
一、什麼是KMP演算法
Knuth-Morris-Pratt 字串尋找演算法(常簡稱為 “KMP演算法”)是在一個“主文本字串” S 內尋找一個“詞” W 的出現,,以此避免對以前匹配過的字元重新檢查。(在原串中匹配模式串)
二、KMP示範
http://staff.ustc.edu.cn/~ypb/jpkc/flash/Find_KMP.swf
三、KMP原理
KMP是一種最常見的改進演算法,它可以在匹配過程中失配的情況下,有效地多往後面跳幾個字元,加快匹配速度。
在KMP演算法中有個數組,叫做首碼數組,也有的叫,每一個模式串都有一個固定的next數組,,當然它描述的也是子串的對稱程度,程度越高,值越大,當然之前可能出現再匹配的機會就更大。
對於next數組的理解,參見http://blog.csdn.net/yearn520/article/details/6729426#t0
[cpp] view plaincopy
- void SetPrefix(const char *Pattern, int prefix[])
- {
- int i;
- int len=strlen(Pattern);//模式字串長度。
- prefix[0]=0;
- for(i=1; i<len; i++)
- {
- int k=prefix[i-1];
- //不斷遞迴判斷是否存在子對稱,k=0說明不再有子對稱,Pattern[i] != Pattern[k]說明雖然對稱,但是對稱後面的值和當前的字元值不相等,所以繼續遞推
- while( Pattern[i] != Pattern[k] && k!=0 )//例i等於14時,求prefix[14]的值
- k=prefix[k-1]; //繼續遞迴
- if( Pattern[i] == Pattern[k])//找到了這個子對稱,或者是直接繼承了前面的對稱性,這兩種都在前面的基礎上++
- prefix[i]=k+1;
- else
- prefix[i]=0; //如果遍曆了所有子對稱都無效,說明這個新字元不具有對稱性,清0
- }
- prefix[0]=-1;
- }
四、測試小例
[cpp] view plaincopy
- #include <iostream>
- #include <cstring>
- #include <string>
- using namespace std;
-
- string sorg;
- string spat;
- int prefix[10000];
- int result[20];
-
- void init()
- {
- sorg="";
- spat="";
- memset(prefix,0,sizeof(int)*10000);
- //memset(result,0,sizeof(int)*20);
- }
- void setprefix(string temp,int next[])
- {
- int len=temp.size();
- next[0]=0;
-
- for(int i=1;i<len;i++)
- {
- int k=next[i-1];
-
- while(temp[k]!=temp[i]&&k!=0)
- k=next[k-1];
-
- if(temp[k]==temp[i])
- next[i]=k+1;
- else
- next[i]=0;
- }
-
- next[0]=-1;
-
- for(int i=0;i<len;i++)
- if(next[i]>=1)
- next[i]=next[i]-1;
- }
-
- int kmp(string s1,string s2)
- {
- int number=0;
- int i=0;
- int j=0;
- while(i<(int)s1.size()&&j<(int)s2.size())
- {
- if(j==-1||s1[i]==s2[j])
- {
- i++;
- j++;
- }
- else
- j=prefix[j];
-
- if(j==s2.size())
- {
- i=i-j+1;
- j=0;
- number++;
- }
- }
-
- return number;
- }
- int main()
- {
- int t;
- cin>>t;
- memset(result,0,sizeof(int)*20);
- for(int i=0;i<t;i++)
- {
- init();
- //cout<<"input spat string:"<<endl;
- cin>>spat;
-
- //cout<<"input sorg string:"<<endl;
- cin>>sorg;
-
- setprefix(spat,prefix);
- result[i]=kmp(sorg,spat);
- }
-
- for(int j=0;j<t;j++)
- cout<<result[j]<<endl;
-
-
- return 0;
- }
KMP演算法學習