TA的每日心情 | 擦汗 昨天 10:19 |
|---|
签到天数: 1804 天 连续签到: 6 天 [LV.Master]伴坛终老 管理员
退休的新人
  
- UID
- 1
- 小七币
- 3624
- 贡献
- 33
- 在线时间
- 5310 小时
- 注册时间
- 2011-12-19
     
|
void preKMP(const char *const pSub,char *const pIndex) {//KMP索引计算方法
int intIndex=-1;//无法找到相同的字符的索引
pIndex[0]=intIndex;//第一个默认为找不到的
for (size_t i=1;i<strlen(pSub);++i)//遍历所有子串,从第二个字符开始遍历
{
//找不到的情况下
while(intIndex>-1 && pSub[intIndex+1]!=pSub[i])
intIndex=pIndex[intIndex];
//找到的情况下进行索引纠正
if(pSub[intIndex+1]==pSub[i])
++intIndex;//找到的情况进行索引进行赋值
//最后确定索引
pIndex[i]=intIndex;
}
}
void KMP(const char *const pStr,const char *const pSub)
{
char *arrIndex=new char[strlen(pSub)*sizeof(char)];//先分配一个索引数组与子字符串对应
preKMP(pSub,arrIndex);//准备好数组索引
size_t intIndex=arrIndex[0];
for (size_t i=0;i<strlen(pStr);++i)
{
while(intIndex>-1 && pSub[intIndex+1]!=pStr[i])
intIndex=arrIndex[intIndex];
if(pSub[intIndex+1]==pStr[i])
intIndex++;
if (intIndex==strlen(pSub)-1)
{
intIndex=arrIndex[intIndex];
printf("..............\n");
}
}
delete[] arrIndex;
}
|
|