gpt4 book ai didi

在字谜程序中找不到错误

转载 作者:行者123 更新时间:2023-11-30 17:24:06 25 4
gpt4 key购买 nike

我在以下字谜程序中找不到错误所在。

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

int is_anagram(char* s1, char* s2){
int i;
char count[256] = {0};
if(NULL == s1 || NULL == s2) return 0;
for(i = 0; (s1[i] && s2[i]); i++){
count[s1[i]]++;
count[s2[i]]--;
}
if(s1[i] && s2[i]) return 0;
for(i = 0; i < 256; i++)
if(count[i]) return 0;

return 1;
}

int main(){
int i;
char* cases = malloc(10);
char* str = malloc(500000);
char* str1;
char* str2;
if(NULL == cases || NULL == str) return 0;
fgets(cases,10,stdin);
for(i = 0; i < atoi(cases); i++){
fgets(str,500000,stdin);
str1 = strtok(str," ");
str2 = strtok(NULL," ");
if(NULL == str1 || NULL == str2){
printf("\nNO");
return 0;
}
if(is_anagram(str1,str2)){
printf("\nYES");
}
else{
printf("\nNO");
}
}
free(str);
return 0;
}

我试图验证输入的数字是否是字谜。

我输入 3 个字符串来查找是否是字谜

i/p:3abc abc - 是abc ba - 否a1b2c3 abc123 - 是

对于某些 i/p,我无法获得正确的 o/p,例如第二个带有大量空格的字符串。如何进一步优化

最佳答案

目前,此行无用(始终为 false):

if(s1[i] && s2[i]) return 0;

您的意思可能是:

if(s1[i] || s2[i]) return 0;

此外,您的代码还可以在 count 数组中使用负索引,因为您使用带符号字符作为数组索引。不过,对于普通的 ASCII 输入,你没问题。

关于在字谜程序中找不到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27331408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com