编程之美:字符串移位包含的问题
题目:
给定两个字符串s1 和 s2,要求判定s2是否能够被s1做循环移位(rotate)得到的字符串包含。
例如,给定s1=AABCD, s2=CDAA,返回true;给定,s1=ABCD, s2=ACBD, 返回false。
下面是我的写的代码,运行是正确的。但是不知道有没有问题。总感觉有的地方不对。
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <malloc.h>char *s1 = "AABCD";char *s2 = "CDAA";int main(){ char *p, *temp; int i, length; length = strlen(s1); for (i = 0; i < length; i++) { p = malloc(length + 1); p = strcpy(p, s1); temp = strncat(p+i, s1, i); p = strcpy(p, temp); if (strstr(p, s2)) { printf("p is %s, s2 is %s\n", p, s2); free(p); return 1; } else { free(p); } } printf("no substring s2 in the rotate of s1\n"); return 0;}#include <stdio.h>#include <string.h>int contains(const char* s1, const char* s2){ int length1 = strlen(s1); int length2 = strlen(s2); int i, j, flag; for (i = 0; i < length1; ++i) { for (j = 0, flag = 1; j < length2; ++j) { if (s1[(i + j) % length1] != s2[j]) { flag = 0; break; } } if (flag) { return 1; } } return 0;}int main(void){ char s1[100], s2[100]; scanf("%s%s", s1, s2); printf("%s", contains(s1, s2) ? "true" : "false"); return 0;}