首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

编程之美:字符串移位包含的有关问题

2012-08-16 
编程之美:字符串移位包含的问题题目:给定两个字符串s1 和 s2,要求判定s2是否能够被s1做循环移位(rotate)得

编程之美:字符串移位包含的问题
题目:
给定两个字符串s1 和 s2,要求判定s2是否能够被s1做循环移位(rotate)得到的字符串包含。
例如,给定s1=AABCD, s2=CDAA,返回true;给定,s1=ABCD, s2=ACBD, 返回false。

下面是我的写的代码,运行是正确的。但是不知道有没有问题。总感觉有的地方不对。

C/C++ code
#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;}


[解决办法]
p = malloc(length + 1);//是不是要多申请些空间?strncat(p+i, s1, i);

[解决办法]
2楼++,
P申请的空间就是6个字节,strncat的时候,就溢出了;
The strcat() function appends the src string to the dest string over-
writing the ‘\0’ character at the end of dest, and then adds a termi-
nating ‘\0’ character. The strings may not overlap, and the dest
string must have enough space for the result.
[解决办法]
还要加上s2的长度≤s1的条件。
[解决办法]
C/C++ code
#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;} 

热点排行