这是问题。
对于两个字符串A和B,我们将字符串的相似性定义为两个字符串共有的最长前缀的长度。例如,字符串“ abc”和“ abd”的相似度为2,而字符串“ aaa”和“ aaab”的相似度为3。
计算字符串S与每个后缀的相似度之和。
输入:
第一行包含测试用例T的数量。接下来的T行各包含一个字符串。
输出:
输出T行,其中包含相应测试用例的答案。
限制条件:
1 每个字符串的长度最多为100000,并且仅包含小写字符。
样本输入:
2
阿巴巴
a
样本输出:
11
3
说明:
对于第一种情况,字符串的后缀是“ ababaa”,“ babaa”,“ abaa”,“ baa”,“ aa”和“ a”。这些字符串与字符串“ ababaa”的相似度分别为6,0,3,0,1,1。因此答案是6 + 0 + 3 + 0 + 1 + 1 = 11。
我面临的问题是:
对于小于5的测试用例,它可以正常工作。对于5或更高的5,第一个字符串的输出显示为0。为进行调试,我使用了字符变量k来查找指针所指向的值。计算第一个字符串时,k的值为-54,-56和其他值。对于第一个以外的其他字符串,它可以正常工作。
我什至尝试打印第一个字符串。正在打印一些垃圾值。但是对于小于5的测试用例,它可以正确打印。我给出了以下代码。请帮我。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int test_cases,i,j,*count;
char k; //for testing purpose to determine the character at each iteration
scanf("%d",&test_cases);
count = calloc(test_cases,sizeof(int));
char **strings, *initial_ptr, *current_ptr, *start_ptr;
strings = malloc(test_cases);
for(i=0;i<test_cases;i++)
{
strings[i] = malloc(100000);
scanf("%s",strings[i]);
}
initial_ptr = start_ptr = *strings;
current_ptr = *strings;
//testing
printf("This is the first string: ");
puts(strings[0]);
int temp_count=0;
for(i=0;i<test_cases;i++)
{
current_ptr = initial_ptr = start_ptr = *(strings+i);
temp_count=0;
for(j=0;j<strlen(strings[i]);j++)
{
k = *current_ptr;
while((*current_ptr) && (*current_ptr >= 'a') && (*current_ptr <= 'z'))
{
if(*current_ptr == *initial_ptr)
{
temp_count++;
current_ptr++;
initial_ptr++;
}
else
{
start_ptr++;
current_ptr = start_ptr ;
initial_ptr = *(strings+i) ;
}
}
current_ptr = start_ptr;
count[i]=temp_count;
}
}
for(i=0;i<test_cases;i++)
{
printf("\n%d",count[i]);
}
return 0;
}
最佳答案
count = (int *)calloc(test_cases*sizeof(int),0);
没有意义。
calloc
中的第二个参数是您要分配的元素的大小。该呼叫应显示为:count = calloc(test_cases, sizeof(int));
这也是错误的:
strings = (char **) malloc(test_cases);
应该:
strings = malloc(test_cases*sizeof(char*));
这个:
printf("This is the first string: ");
puts(strings[1]);
具有误导性:它显示第二个字符串。
关于c - 随着I/P大小超过C中的5,程序执行会有所不同,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8552101/