hdu2203(KMP模板)
2015-10-10 01:09
375 查看
参考代码:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<vector> #include<set> #include<map> #include<queue> #include<sstream> #include<string> #include<bitset> using namespace std; typedef long long LL; const LL LINF = (1LL <<63); const int INF = 1 << 31; const int NS = 200010; const int MS = 19; const int MOD = 1000000007; char s1[NS], s2[NS]; int snext[NS]; void getNext(char* pattern, int* next) { //未优化的next数组,字符下标从0开始 int len = strlen(pattern); int j = -1; next[0] = -1; for(int i = 0; i < len;) { while(j >= 0 && pattern[i] != pattern[j]) { j = next[j]; } i++, j++; next[i] = j; } } void getOptNext(char* pattern, int* next) { //优化的next数组,字符下标从0开始 int len = strlen(pattern); int j = -1; next[0] = -1; for(int i = 0; i < len;) { while(j >= 0 && pattern[i] != pattern[j]) { j = next[j]; } i++, j++; if(pattern[i] != pattern[j]) { next[i] = j; } else { next[i] = next[j]; } } } bool KMP(char* target, char* pattern, int* next) { int n = strlen(target); int m = strlen(pattern); int j = 0; for(int i = 0; i < n;) { if(target[i] == pattern[j]) { i++, j++; if(m == j) { return true; } } else { j = next[j]; if(j < 0) { i++, j++; } } } return false; } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); #endif while(~scanf("%s %s", s1, s2)) { int n = strlen(s1); for(int i = 0; i < n; i++) { s1[i + n] = s1[i]; } n <<= 1; s1 = '\0'; getOptNext(s2, snext); bool ans = KMP(s1, s2, snext); if(ans) { puts("yes"); } else { puts("no"); } } return 0; }
相关文章推荐
- Trump成功笔记6
- 链式栈的实现
- 10.10
- Java中字符串中子串的查找共有四种方法(indexof())
- leetcode之First Bad Version
- 链队列
- osgEarth获取经纬度和高程的几种方法
- Leetcode Read N Characters Given Read4
- 0916词法分析
- Trump成功笔记5
- 如何将你牛逼的iOS代码分享到CocoaPod
- PHP知识点系列之一:面向对象基础
- Android开发菜鸟级入门3--定时器
- jquery和css自定义video播放控件。
- 利用Python Paramiko开发linux堡垒机 推荐
- C++工作的心得体会
- 《你必须知道的.NET》读书笔记:方法表初窥
- JavaScript实现Ajax小结
- css学习笔记三
- JSP九大内置对象