赞
踩
上图中我们眼睛可以看出来k的位置 但是在程序中实现呢 ?
- int *Get_next(const char *sub)
- {
- //assert
- int len_sub = strlen(sub);
- int *next = (int*)malloc(sizeof(int) * len_sub);
- assert(next != 0);
-
- next[0] = -1;
- next[1] = 0;
-
- int j = 1;
- int k = 0;
-
- //通过已知推位置 j是已知 则j+1是未知
- while(j+1 < len_sub)//未知位置需要合法 所以做了一个判断
- {
- if(sub[j] == sub[k] || (k==-1))//要么相等k++赋值,要么不相等k一直回退,触发了保底机制(k==-1)
- {
- //next[++j] = ++k;
- k++;
- j++;
- next[j] = k;
- }
- else
- {
- k = next[k];
- }
- }
-
- return next;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- int KMP_Search(const char *str, const char *sub, int pos)//pos代表主串开始查找的下标位置
- {
- assert(str!=NULL && sub!=NULL);
- if(pos<0 || pos>=(int)strlen(str))
- {
- //return -1;
- pos = 0;
- }
-
- int len_str = strlen(str);//主串的长度信息
- int len_sub = strlen(sub);//子串的长度信息
- int i = pos;//主串开始位置
- int j = 0;//子串开始位置
-
-
- int *next = Get_next(sub);
-
- while(i<len_str && j<len_sub)
- {
- if((j==-1) || str[i] == sub[j])//如果相等,两者同时向后走,i++,j++
- {
- i++;
- j++;
- }
- else
- {
- //i不回退
- j = next[j];//next[j] == k
- }
- }
-
- //此时while循环退出 两种情况,要么i走出范围 要么j走出范围
- if(j >= len_sub)//如果子串的j走出范围,找到了,返回i-j
- {
- return i-j;
- }
- else//否则没有找到,匹配失败,返回-1
- {
- return -1;
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。