【问题标题】:Couldnt find error in the anagram program在字谜程序中找不到错误
【发布时间】:2015-02-04 12:56:29
【问题描述】:

我在以下 anagram 程序中找不到错误。

#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 个字符串来查找是否是字谜

我/p: 3 abc abc - 是的 abc ba - 没有 a1b2c3 abc123 - 是的

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

【问题讨论】:

  • 为什么你认为它没有效率?具体是哪个代码?
  • 为什么要优化不正确的代码?
  • 如果它没有为某些输入生成正确的结果,也许你应该在调试器下运行它,同时它正在处理一个失败的输入。
  • 50000 - 因为 49999 还不够,而 50001 太多了。
  • 如果两个字符串之间有很多空格,程序将无法工作

标签: c anagram


【解决方案1】:

目前,这条线是没用的(总是假的):

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

你的意思可能是:

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

此外,您的代码有可能在 count 数组中使用负索引,因为您使用有符号字符作为数组索引。不过,在正常的 ASCII 输入上,你没问题。

【讨论】:

    猜你喜欢
    • 2016-11-01
    • 2021-07-01
    • 2014-06-20
    • 2012-07-22
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多