这里不做研究,只是为个人加深印象而写,以便日后查阅,具体可以参考下面两篇文章,写的比较详细:
http://wenku.baidu.com/view/5045c90cba1aa8114431d994.html
http://www.matrix67.com/blog/archives/115
C++代码
- #include<iostream>
- //获取模式数组
- void GetNext(const char* p,int next[])
- {
- int m=0;
- int n=-1;
- next[0] = -1;
- while (p[m+1] != '/0')
- {
- if (n==-1 || p[m]==p[n])
- {
- ++m;
- ++n;
- if (p[m]!=p[n])
- next[m] = n;
- else
- next[m]=next[n];
- }
- else
- {
- n = next[n];
- }
- }
- }
- //查找匹配位置
- int KMP(const char* pSchar,const char* pDchar,int pos)
- {
- int i = pos;
- int j = 0;
- int index = 0;
- int* next = new int[strlen(pDchar)+1];
- GetNext(pDchar,next);
- while(pSchar[i] != '/0' && pDchar[j] != '/0')
- {
- if (pSchar[i] == pDchar[j])
- {
- ++i;
- ++j;
- }
- else
- {
- index += j - next[j];
- if (next[j] != -1)
- j = next[j];
- else
- {
- j = 0;
- ++i;
- }
- }
- }
- delete[] next;
- if (pDchar[j] == '/0')
- return index;
- else
- return -1;
- }
- void main()
- {
- char* s = "abababaabab";
- char* p = "aaba";
- int index = -1;
- index = KMP(s,p,0);
- if (index != -1)
- printf("从第%d个字符开始匹配",index+1);
- else
- printf("%s","没有找到匹配");
- }