kmp
来源:互联网 发布:c语言 n 编辑:程序博客网 时间:2024/06/06 11:45
KMP
时间复杂度T(n):O(n);
空间复杂度S(n):O(n);
最近打算认真的给字符串补补档,so,kmp这个有意思的字符串算法我也不打算放过了,kmp是处理字符串匹配的一个神器算法,最合适的是在多个串中找一个串,复杂度为字符串的总长度。比较被熟知的匹配我这里就不提了,看到了一个很详细的博客 网址:http://www.cnblogs.com/SYCstudio/p/7194315.html应该能够理解,感觉博主写的真的非常好。
这里提一个我之前做kmp的时候遇到的小trick,如果对于一个串,n %(n – next[n]) == 0那么这个串为循环串,并且循环节的大小就是n – next[n]具体的证明我是不太会说的,大家可以尝试自行手动模拟一下应该更能够理解。
实现:主要直接见代码。
例题:寻找子串位置
codevs1204
Source:
/*created by scarlyw*/#include <cstdio>#include <string>#include <algorithm>#include <cstring>#include <iostream>#include <cmath>#include <cctype>#include <vector>#include <set>#include <queue>inline char read() {static const int IN_LEN = 1024 * 1024;static char buf[IN_LEN], *s, *t;if (s == t) {t = (s = buf) + fread(buf, 1, IN_LEN, stdin);if (s == t) return -1;}return *s++;}///*template<class T>inline void R(T &x) {static char c;static bool iosig;for (c = read(), iosig = false; !isdigit(c); c = read()) {if (c == -1) return ;if (c == '-') iosig = true;}for (x = 0; isdigit(c); c = read()) x = ((x << 2) + x << 1) + (c ^ '0');if (iosig) x = -x;}//*/const int OUT_LEN = 1024 * 1024;char obuf[OUT_LEN], *oh = obuf;inline void write_char(char c) {if (oh == obuf + OUT_LEN) fwrite(obuf, 1, OUT_LEN, stdout), oh = obuf;*oh++ = c;}template<class T>inline void W(T x) {static int buf[30], cnt;if (x == 0) write_char('0');else {if (x < 0) write_char('-'), x = -x;for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 + 48;while (cnt) write_char(buf[cnt--]);}}inline void flush() {fwrite(obuf, 1, oh - obuf, stdout);}/*template<class T>inline void R(T &x) {static char c;static bool iosig;for (c = getchar(), iosig = false; !isdigit(c); c = getchar())if (c == '-') iosig = true;for (x = 0; isdigit(c); c = getchar()) x = ((x << 2) + x << 1) + (c ^ '0');if (iosig) x = -x;}//*/const int MAXN = 100 + 10;char s[MAXN], t[MAXN];int p[MAXN];inline void get_next(char *s) {int j = 0, len = strlen(s + 1);for (int i = 2; i <= len; ++i) {while (j && s[j + 1] != s[i]) j = p[j];if (s[j + 1] == s[i]) ++j;p[i] = j;}}inline void match(char *s, char *t) {int j = 0, lens = strlen(s + 1), lent = strlen(t + 1);for (int i = 1; i <= lens; ++i) {while (j && s[i] != t[j + 1]) j = p[j];if (t[j + 1] == s[i]) ++j;if (j == lent) std::cout << i - lent + 1, exit(0);}}int main() {scanf("%s", s + 1), scanf("%s", t + 1);get_next(t), match(s, t);return 0;}
阅读全文
1 0
- KMP
- KMP
- KMP
- KMP
- KMP
- KMP
- kmp
- kmp
- KMP
- kmp
- KMP
- KMP
- KMP
- kmp
- KMP
- KMP
- kmp
- KMP
- mysql主从复制、基于gtid的主从复制、并行复制、半同步
- 把数组排成最小的数java实现
- Android Framework增加新的系统服务详解
- 自定义圆形刻度盘
- Kotlin 标准库扩展函数
- kmp
- 【安全牛学习笔记】KALI版本更新(第一个ROLLING RELEASE)和手动漏洞挖掘(SQL注入)
- Hello级别的Servlet
- Android NoClassDefFoundError崩溃问题
- crontab 保存并退出
- 1000: 整数a+b
- 自定义View实现 android圆形统计图及百分比显示
- 递归简单总结
- shell脚本比较两个文件夹