Kattis - String Matching(kmp)
2017-01-13 21:02
429 查看
String Matching
Input
The input consists of several test cases. Each test case consists of two lines, first a non-empty pattern, then a non-empty text. Input is terminated by end-of-file. The input file will not be larger than 5 Mb.Output
For each test case, output one line containing the positions of all the occurences of pattern in text, from first to last, separated by a single space.Sample Input 1 | Sample Output 1 |
---|---|
p Popup helo Hello there! peek a boo you speek a bootiful language anas bananananaspaj | 2 4 5 7 |
题意
多组输入,每组两行,模式串和对比串,输出上面的模式串在下面的字符串中的所有位置下标,下标从0开始思路1
KMP算法,套个模版就可以了思路2
用string的find,str2.find(str1,x),关于这个函数的用法http://www.cplusplus.com/reference/string/string/find/代码1
#include<stdio.h> #include<string.h> using namespace std; int const MAXM = 4000000; char s[MAXM], t[MAXM]; int next[MAXM], n; int shuchu[MAXM]; void get_next() { next[0] = -1; int i = 0, j = -1; while (t[i] != '\0') { if (j == -1 || t[i] == t[j]) { i++; j++; next[i] = j; } else j = next[j]; } } int KMP() { get_next(); int i = 0, j = 0, ans = 0, len = strlen(t); while (s[i]) { if (j == -1 || s[i] == t[j]) { i++; j++; } else j = next[j]; if (j == len) { j = next[j]; shuchu[ans++] = i; } } return ans; } int main() { while (gets(t)) { gets(s); int ss = KMP(); for (int i = 0; i < ss; i++) { if (i)printf(" "); printf("%d", shuchu[i]-strlen(t)); } puts(""); } }
代码2
#include<bits/stdc++.h> using namespace std; int main(){ string str1,str2; int cnt[100000]; while(getline(cin,str1)){ getline(cin,str2); int pos=0,x=0; while(str2.find(str1,x)!=-1&&x<str2.size()){ cnt[pos++]=str2.find(str1,x); x=cnt[pos-1]+1; } for(int i=0;i<pos;i++){ printf("%d%c",cnt[i],i==pos-1?'\n':' '); } } return 0; }
相关文章推荐
- python-append函数,得到的结果为None
- java的引用传递
- html 文本 标签
- //4. 编写一个函数reverse_string(char * string)(递归实现) //实现:将参数字符串中的字符反向排列。 //要求:不能使用C函数库中的字符串操作函数。
- 面向对象(七)
- 学习笔记:Ubuntu 16.04 下NFS服务器的安装
- 开发工具小技巧
- python程序如何在生产和测试环境自动调用对应的配置文件
- POJ 2251 Dungeon Master(BFS最短路)
- 怀旧老游戏
- LeetCode - 217. Contains Duplicate - 思路详解 - C++
- 遗传算法与直接搜索工具箱学习笔记 九-----遗传算法举例
- 字符串的反码
- 驱动10.nor flash
- 个人代码备忘录-时间戳
- oracle表空间表分区详解及oracle表分区查询使用方法(转+整理)
- C语言 · 9-1九宫格
- 欧拉函数的O( sqrt(n) ) 求法的迷之(小)优化
- 远程桌面无法复制粘贴
- 洛谷 P1025 数的划分