AABCD CDAA ASD ASDF
yes no
题目分析:两种做法,自己敲一边kmp,或者直接调用strstr,首先l1 < l2直接输出no,否则将s1复制一次接在后面当作母串,s2当作模式串
KMP:
#include <cstdio> #include <cstring> int const MAX = 1e5 + 5; int next[MAX], l1, l2, ll1; char ss1[MAX], s2[MAX]; char s1[2 * MAX]; void get_next() { int i = 0, j = -1; next[0] = -1; while(s2[i] != '\0') { if(j == -1 || s2[i] == s2[j]) { i++; j++; if(s2[i] == s2[j]) next[i] = next[j]; else next[i] = j; } else j = next[j]; } } bool KMP() { get_next(); int i = 0, j = 0; while(s1[i] != '\0') { if(j == -1 || s1[i] == s2[j]) { i++; j++; } else j = next[j]; if(j == l2 - 1) return true; } return false; } int main() { while(scanf("%s %s", ss1, s2) != EOF) { ll1 = strlen(ss1); l1 = strlen(s1); l2 = strlen(s2); if(ll1 < l2) { printf("no\n"); continue; } strcpy(s1, ss1); strcat(s1, ss1); if(KMP()) printf("yes\n"); else printf("no\n"); } }
#include <cstdio> #include <cstring> int const MAX = 1e5 + 5; int l1, l2, ll1; char ss1[MAX], s2[MAX]; char s1[2 * MAX]; int main() { while(scanf("%s %s", ss1, s2) != EOF) { ll1 = strlen(ss1); l1 = strlen(s1); l2 = strlen(s2); if(ll1 < l2) { printf("no\n"); continue; } strcpy(s1, ss1); strcat(s1, ss1); if(strstr(s1, s2)) printf("yes\n"); else printf("no\n"); } }
原文地址:http://blog.csdn.net/tc_to_top/article/details/43793609