OR108. 字符串旋转
描述
输入描述
2个不为空的字符串(说明:输入一个字符串以英文分号";"分割为2个字符串)输出描述
输出true或false(表示是否能按要求匹配两个字符串)示例1
输入:
youzan;zanyou
输出:
true
示例2
输入:
youzan;zyouan
输出:
false
C 解法, 执行用时: 1ms, 内存消耗: 376KB, 提交时间: 2020-05-20
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<assert.h> char* mysubstr(char* srcstr, int offset, int length) { assert(srcstr != NULL); int total_length = strlen(srcstr); int real_length = ((total_length - offset) >= length ? length : (total_length - offset)) + 1; char *tmp; if (NULL == (tmp = (char*) malloc(real_length * sizeof(char)))) { printf("Memory overflow . \n"); exit(0); } strncpy(tmp, srcstr + offset, real_length - 1); tmp[real_length - 1] = '\0'; return tmp; } int main() { char str[100]; char strleft[100]; char strright[100]; char str1[100]; char str2[100]; char str3[100]; int count = 0; int i = 0; int flag = 0; scanf("%s", str); for (i = 0; i < strlen(str); i++) { if (';' == str[i]) break; count++; } strcpy(strleft, strtok(str, ";")); strcpy(strright, strtok(NULL, ";")); for (i = 0; i < strlen(strleft); i++) { strcpy(str1, mysubstr(strleft, 0, i)); strcpy(str2, mysubstr(strleft, i, count)); strcpy(str3,strcat(str2, str1)); //printf("%s %s %s\n", str1, str2, strright); if (0 == strcmp(strright, str3)) flag = 1; } if (1 == flag) printf("true"); else printf("false"); return 0; }
C 解法, 执行用时: 2ms, 内存消耗: 268KB, 提交时间: 2019-07-31
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<assert.h> char* mysubstr(char* srcstr, int offset, int length) { assert(srcstr != NULL); int total_length = strlen(srcstr); int real_length = ((total_length - offset) >= length ? length : (total_length - offset)) + 1; char *tmp; if (NULL == (tmp = (char*) malloc(real_length * sizeof(char)))) { printf("Memory overflow . \n"); exit(0); } strncpy(tmp, srcstr + offset, real_length - 1); tmp[real_length - 1] = '\0'; return tmp; } int main() { char str[100]; char strleft[100]; char strright[100]; char str1[100]; char str2[100]; char str3[100]; int count = 0; int i = 0; int flag = 0; scanf("%s", str); for (i = 0; i < strlen(str); i++) { if (';' == str[i]) break; count++; } strcpy(strleft, strtok(str, ";")); strcpy(strright, strtok(NULL, ";")); for (i = 0; i < strlen(strleft); i++) { strcpy(str1, mysubstr(strleft, 0, i)); strcpy(str2, mysubstr(strleft, i, count)); strcpy(str3,strcat(str2, str1)); //printf("%s %s %s\n", str1, str2, strright); if (0 == strcmp(strright, str3)) flag = 1; } if (1 == flag) printf("true"); else printf("false"); return 0; }