hdu 2203 kmp+strstr两种方法代码
2016-01-17 18:08
316 查看
亲和串
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 10763 Accepted Submission(s): 4899
Problem Description
人随着岁数的增长是越大越聪明还是越大越笨,这是一个值得全世界科学家思考的问题,同样的问题Eddy也一直在思考,因为他在很小的时候就知道亲和串如何判断了,但是发现,现在长大了却不知道怎么去判断亲和串了,于是他只好又再一次来请教聪明且乐于助人的你来解决这个问题。
亲和串的定义是这样的:给定两个字符串s1和s2,如果能通过s1循环移位,使s2包含在s1中,那么我们就说s2 是s1的亲和串。
Input
本题有多组测试数据,每组数据的第一行包含输入字符串s1,第二行包含输入字符串s2,s1与s2的长度均小于100000。
Output
如果s2是s1的亲和串,则输出"yes",反之,输出"no"。每组测试的输出占一行。
Sample Input
AABCD CDAA ASD ASDF
Sample Output
yes no
思路:把主串循环一圈,相当于得到了这些个串:
ABCDA
BCDAA
CDAAB
DAABC
这么些个子串也可以想象成一个串:AABCD|AABCD。
|后边表示循环的内容。
这个时候我们可以用KMP来实现:
#include<stdio.h> #include<string.h> using namespace std; char aa[100005]; char b[100005]; char a[300000]; int next[100005]; int lena,lenb; void set_naxt()//子串的next数组 { int i=0,j=-1; next[0]=-1; while(i<lenb) { if(j==-1||b[i]==b[j]) { i++; j++; next[i]=j; } else j=next[j]; } } int kmp() { int i=0,j=0; set_naxt(); while(i<lena) { if(j==-1||a[i]==b[j]) { i++;j++; } else j=next[j]; if(j==lenb) return 1; } return 0; } int main() { while(~scanf("%s%s",aa,b)) { strcpy(a,aa); strcat(a,aa); lena=strlen(a); lenb=strlen(b); if(kmp()) { printf("yes\n"); } else printf("no\n"); if(strstr(a,b)!=0) printf("yes\n"); else printf("no\n"); } }也可以用函数strstr实现:
#include<stdio.h> #include<string.h> using namespace std; char aa[100005]; char b[100005]; char a[300000]; int main() { while(~scanf("%s%s",aa,b)) { strcpy(a,aa); strcat(a,aa); if(strstr(a,b)!=0) printf("yes\n"); else printf("no\n"); } }
相关文章推荐
- PHP - 防止 XSS(跨站脚本攻击)
- 使用springMVC上传文件
- Python异常处理总结
- [转载]TFS源代码管理
- 关于跨域
- Python: Windows下pip安装库出错:Microsoft Visual C++ 9.0 is required < Unable to find vcvarsall.bat
- 钉钉服务器端SDK PHP版
- urllib中的urlretrieve提示错误:No such file or directory
- 4、函数
- Python多进程(multiprocessing)一
- sublime编辑器怎样高速输入PHP头部版本号声明
- git原始源代码编译
- 解决jetty运行时,出现A full JDK (not just JRE) is required问题
- c++异常处理
- 2016代码反思
- QT中PRO文件写法
- 从头认识java-18.2 基本的线程机制(3)-线程的返回与sleep
- 更新Android&nbsp;SDK之后Eclipse…
- java.lang.ClassNotFoundException…
- 面向对象概述、类与对象、封装、构造函数、this关键字