面试题30:KMP 字符串查找
2024-08-30 19:59:15
参考:http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html
自己写的很简单的KMP字符串匹配
int KMP(string s,string p){
int pLen = p.length();
int* next = new int[pLen];
next[] = -; int k = -;
int j = ;
while(j < pLen - ){
if(k == - || p[k] == p[j]){
k++;
j++;
next[j] = k;
}else{
k = next[k];
}
} //print next array;
for(int k=;k<pLen;k++){
std::cout << next[k]<< ",";
}
std::cout << std::endl; j = ;
size_t i = ;
size_t sLen = s.length();
while(i<sLen && j < pLen){
if(j == - || s[i] == p[j]){
i++;
j++;
}else{
j = next[j];
}
} delete next;
if(j == pLen){
return i - j;
}else{
return -;
}
}
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
class Solution {
public:
char *strStr(char *haystack, char *needle) {
if(haystack == nullptr || needle == nullptr) return nullptr; int i = ,j =;
int start = ;
while(haystack[i] != '\0' && needle[j] != '\0'){
if(haystack[i] == needle[j]){
i++;
j++;
}else{
start++;
i = start;
j = ;
}
}
if(needle[j] == '\0') return haystack+start;
else return nullptr;
}
};
最新文章
- ASP.NET Core 中文文档 第二章 指南 (09) 使用 Swagger 生成 ASP.NET Web API 在线帮助测试文档
- 【Alpha】Daily Scrum Meeting第三次
- BeanUtils设置字段值失败问题
- 51nod1188 最大公约数之和 V2
- Java虚拟机工作原理具体解释
- 关于shell环境变量的思考
- C语言基础知识小总结(2)
- 向MyEclipse中导入项目要注意的问题
- Unity四种路径总结
- Android中 Bitmap Drawable Paint的获取、转换以及使用
- mysql8.0.13修改密码
- [ SSH框架 ] Spring框架学习之一
- 读Zepto源码之内部方法
- 让策划也能轻松修改数据的方法:运用Excel2Json2Object插件将xml表格转为Object导入脚本
- 关于Phabricator Arcanist以及提交项目代码
- 离线手动部署docker镜像仓库——harbor仓库(HTTPS)
- [sklearn] 官方例程-Imputing missing values before building an estimator 随机填充缺失值
- 织梦 列表页 list标签 按照自已设置的方式排序
- 《Effective Java》读书笔记一(创建与销毁对象)
- Android 开发之Android 应用程序如何调用支付宝接口