c - 如果一个字符串是其他字符串的旋转。所有测试用例未运行

标签 c string pointers

我使用连接第二个字符串然后搜索其中的第一个字符串的逻辑。 但由于某种原因,该代码并不适用于所有测试用例。

示例

s1 = rahul , s2 = hulra

s2.s2 = hulrahulra

然后使用strstr()函数在s2.s2中搜索s1

#include <stdio.h>
#include <string.h>


int ifRotation(char *s1, char *s2)
{
    int l1 = strlen(s1);
    int l2 = strlen(s2);

    char str1[l1], str2[l2+ l2];

    int i;
    i = 0;

    while(*s1 != '\0')
    {
        str1[i] = *s1;
        i++;
        s1++;   
    }
    i = 0;
    while(*s2 != '\0')
    {
        str2[i] = *s2;
        i++;
        s2++;   
    }

    strcat(s2, s2);

    if(strstr(s2, s1))
    {
        return 1;
    }
    return 0;
}

int main() {
    //code

    int queries;

    scanf("%d", &queries);
    int array[queries];
    char str1[100];
    char str2[100];
    int i = 0;
    while(i < queries)
    {
        scanf("%s", &str1);
        scanf("%s", &str2);
        array[i] = ifRotation(str1, str2);
        i++;
    }

    i = 0;
    while(i < queries)
    {
        printf("%d\n", array[i]);
        i++;
    }

    return 0;
}

请告诉我代码有什么问题?

最佳答案

您只是从一个字符串复制到另一个字符串,并且复制例程有几个问题。

  1. char str1[l1] 不够大。它应该是char str1[l1 + 1]。额外的 1 用于空字符。

  2. 字符串应始终以空字符 '\0' 结尾。

  3. s1s2 递增,直到到达空字符,因此到那时 s1s2 为空。

尝试使用以下代码复制字符串,您将看到 s1/s2 将为空,str1/str2 只是原始 s1/的副本s2.

您可以按如下方式修复复制:

char str1[l1 + 1], str2[l2 + 1];

int i;
i = 0;
while(*s1 != '\0')
{
    str1[i] = *s1;
    i++;
    s1++;
}
str1[i] = '\0';

i = 0;
while(*s2 != '\0')
{
    str2[i] = *s2;
    i++;
    s2++;
}
str2[i] = '\0';

printf("s1=%s, s2=%s, str1=%s, str2=%s\n", s1, s2, str1, str2);
//output: s1=, s2=, str1=old_s1, str2=old_s2

但这并没有真正取得任何成果。如果您只想检查 "rahul" 是否与 "hulra" 相反,请保持 s1 不变,复制 s2 以相反的顺序转换为 reverse_s2,并按如下方式比较两个字符串:

#include <stdio.h>
#include <string.h>

int ifRotation(const char *s1, const char *s2)
{
    if(!s1 || !s2)
        return 0;

    int len2 = strlen(s2);
    char reverse_s2[len2 + 1];

    //copy s2 to reverse_s2 in reverse order:
    int i = 0;
    for(i = 0; i < len2; i++)
        reverse_s2[i] = s2[len2 - i - 1];
    reverse_s2[i] = '\0'; //add null character

    int result = strcmp(s1, reverse_s2) == 0;

    return result;
}

int main(void) 
{
    printf("%d\n", ifRotation("rahul", "hulra"));
    printf("%d\n", ifRotation("rahul", "luhar"));
    return 0;
}

关于c - 如果一个字符串是其他字符串的旋转。所有测试用例未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51499996/

相关文章:

c++ - 检测字符串中的负整数

c++ - 带有随机指针的链表的深拷贝

C++: "this"指针没用吗?

c - 如何在汇编程序中使用 C 库?

c - 无变量字符串反转

c - C程序中的数组

c# - 为什么 TextInfo.ToTitleCase 在字母全部为大写的字符串上不能正常工作?

c - 如何从函数 A 返回一个数组,然后函数 B 获取这个数组

c - 这个C代码段有什么问题?当我不分配 t 它工作正常

c++ - C & C++ 中 sizeof() 运算符的返回值