KMP算法复习
来源:互联网 发布:手机淘宝上怎么退货 编辑:程序博客网 时间:2024/06/09 19:18
g++ (Ubuntu 4.9.2-10ubuntu13) 4.9.2下编译和运行通过
#include<iostream>#include<string.h>using namespace std;int * getnext(char* substr){ unsigned int i = 0; int j = -1; int n = strlen(substr); int *next = new int(n); next[0] = -1; while (i < strlen(substr)) { if (j == -1 || substr[i] == substr[j]) { ++i; ++j; next[i] = j; } else { j = next[j]; } } return next;}int KMP(char* str, char* substr){ int unsigned i = 0, j = 0; int *next; next = getnext(substr); while (i < strlen(str) && j < strlen(substr)) { if (str[i] == substr[j]) { ++i; ++j; } else { j = next[j]; if (j == -1) { j = 0; ++i; } } } if (j == strlen(substr)) return (i - strlen(substr)); else return 0;}int main(){ char* str = "abababc"; char* substr = "abc"; int i = KMP(str, substr); cout << "This is the result:" << endl; cout << i << endl;//result = 4 return 0;}
我在牛客网上implement str的解答:(不知道为什么通不过测试,请指教!)
class Solution {public: int strStr(char *haystack, char *needle) { int i = 0; int j = 0; int m = strlen(haystack); int n = strlen(needle); int *next = new int[n]; getnext(needle, next); while (i < m && j < n) { if (j == -1 || haystack[i] == needle[j]) { ++i; ++j; } else { j = next[j]; } } if (j >= n) return (i - j); else return -1; } void getnext(char *needle, int next[]) { int i = 0, j = -1; int n = strlen(needle); next[0] = -1; while (i <n) { if (j == -1 || needle[i] == needle[j]) { ++i; ++j; next[i] = j; } else j = next[j]; } }};
1 0
- KMP算法复习
- KMP算法复习
- 【各种算法】【kmp】复习
- KMP匹配算法复习。。
- KMP算法复习【+继续学习】
- Binary String Matching---KMP算法,再次复习
- KMP算法复习总结:Bzoj3620&&Bzoj3670
- [数据结构]KMP算法(个人复习用)
- kmp复习
- 一步一步复习数据结构和算法基础-KMP算法
- KMP 复习 再续~~
- KMP复习整理
- KMP复习小结
- 扩展KMP复习小记
- KMP复习 找字符串
- [复习]KMP 字符串匹配
- 数据结构与算法复习(20)—— KMP 与字符串算法及其扩展
- (笔试前复习)比KMP算法更简单更快的字符串匹配算法
- C语言标准发展历史以及各种libc实现
- 在CentOS7中systemctl命令
- ios 内购流程
- PHP 删除数组中特定元素
- 【STM8L】STM8L之按键中断
- KMP算法复习
- Ubuntu 英文语言转为中文语言
- centos6.5/centos7安装部署企业内部知识管理社区系统wecenter
- ios 内购服务器验票(漏单处理)
- 《代码简洁之道》总结五之简洁的格式
- 一周IT博文精选TOP10(第十期)
- 阿里云使用一键安装包后取消phpwind的首页
- Maven教程-搭建Maven环境
- 博客搭建系列一:用hexo搭建个人博客