- UID
- 2198
注册时间2005-6-29
阅读权限255
最后登录1970-1-1
副坛主
该用户从未签到
|
看了一篇KMP算法的文章,对数学公式有点没绕明白,干脆自己琢磨琢磨吧。
Link: http://blog.csdn.net/yaochunnian/article/details/7059486
自己在纸上画了画,逻辑应该是找重复,简单实现了一个自己的逻辑,改天在继续研究。
我的想法是这样的
Test1 :
a a a b
0 0 1 2
Test2 :
a b a b c d
0 0 0 1 2 0
然后根据返回值 j,来判断如何处理。
- void GetNextval(char const* pstr, int nlen, int* Value)
- {
- int i = 1;
- int k = 0;
- int nMax = 0;
- memset( Value, 0, nlen * sizeof(int));
- while( i < nlen )
- {
- // "abaabac";
- if( *(pstr + i) == *(pstr) ) //循环的if部分
- {
- nMax = k = 0;
- do
- {
- nMax ++;
- Value[i + k + 1] = nMax;
- k++;
- } while ( k < (nlen - i) &&
- *(pstr + i + k) == *(pstr + k) );
- i += k;
- continue;
- }
- i++;
- }
- }
- void GetNextvalEx(char const* pstr, int nlen, int* Value)
- {
- int i = 1;
- int k = 0;
- int nMax = 0;
- memset( Value, 0, nlen * sizeof(int));
- while( i < nlen-1 )
- {
- // "aaaaaab";
- // "0012345";
- if( * pstr == *(pstr + i) ) //循环的if部分
- {
- nMax = k = 0;
- do
- {
- ++k ;
- Value[i + k ] = ++nMax;
- } while ( i + k < nlen-1 &&
- *(pstr + k) == *(pstr + i + k) );
- i += k;
- continue;
- }
- i++;
- }
- }
- int KmpSearch(char const* src, int len1, char const* dest, int len2, int const* Value, int pos)
- {
- int i = pos;
- int j = 0;
- int nIndex = 0;
- while ( i < len1 && j < len2 )
- {
- if( src[i] == dest[j] )
- {
- ++i;
- ++j;
- }
- else
- {
- j = Value[j];
- if ( src[i] != dest[j] )
- {
- if ( j != 0 ) // j > 0
- j = 0;
- ++i;
- }
- }
- }
- if( j == len2 )
- nIndex = i-len2;
- else
- nIndex = -1;
- return nIndex;
- }
- int main()
- {
- std::string src = "abababc";
- std::string prn = "abc";
- int* nextval = new int[prn.size()];
- GetNextval(prn.data(), prn.size(), nextval);
- int nIndex = KmpSearch(src.data(), src.size(), prn.data(), prn.size(), nextval, 0);
- // delete ...
- }
复制代码
|
|