问题源自数据结构书。
问题:字符串src中含有模式串pat的个数
举例:src= 00000111111111101010111010101001
pat=110
src中含有多少个pat?
分析:
没有回溯的KMP算法。
1)首先实现一个next[]数字,其中的值,是匹配失误之后的下一次匹配的位置。next[0]=-1; next[1]=0;后面的多数都不是0。这个实际是一个KMP的匹配过程;
2)然后把pat在src中进行匹配,又是一个KMP的匹配过程。
代码:
- const int pat_length = 3;
- int src_length = 0;
- // 计算next[],一次KMP算法
- bool nextPos(const char* pPat, int* next)
- {
- int k = -1;
- next[0] = k;
- int index = 0;
- do {
- if ( (-1 == k) || pPat[index] == pPat[k] )
- {
- k++;
- index++;
- next[index] = k;
- }
- else
- {
- k = next[k];
- }
- } while ( index < pat_length - 1 );
- return true;
- }
- // pat与src进行匹配,一次KMP算法
- int match(const char* pSrc, const char* pPat, const int* next)
- {
- int times = 0;
- int srcIndex = 0;
- int patIndex = 0;
- while ( patIndex < pat_length && srcIndex < src_length )
- {
- if ( patIndex == -1 || pSrc[srcIndex] == pPat[patIndex] )
- {
- patIndex++;
- srcIndex++;
- }
- else
- {
- patIndex = next[patIndex];
- }
- if ( patIndex == pat_length ) //match
- {
- times++;
- patIndex = 0;
- }
- }
- return times;
- }
- //测试程序
- int main(int argc, char* argv[])
- {
- using namespace std;
- char src[] = "acabaabaabcacaabc";
- char pat[] = "abaabcac";
- src_length = sizeof(src);
- int next[pat_length];
- int times = 0;
- if ( nextPos(pat, next) )
- {
- times = match(src, pat, next);
- cout << "times:" << times << endl;
- }
- getchar();
- return 0;
- }