【问题标题】:PSET5 Speller Huge Number of Misspelled WordsPSET5 Speller 大量拼写错误的单词
【发布时间】:2020-02-25 03:50:46
【问题描述】:

我一直在运行解决方案,但发现大量拼写错误的单词。 单词拼写错误:15904 与员工的单词拼写错误:955 相比

除此之外,字数准确,运行时间也很好。 我怀疑问题可能来自检查/加载功能,但我不确定是什么原因造成的。 其他一些代码在检查函数中实现了“转小写”,但我认为 (strcasecmp) 可以完成字符串之间的比较工作,而忽略大小写。

检查功能

bool check(const char *word)
{

    int hashInt = hash(word);

    if (table[hashInt] == NULL)
    {
        return 1;
    }

    node *cursor = table[hashInt];

    while (cursor != NULL)
    {

        int i = strcasecmp(cursor -> word, word);

        if (i == 0)
        {
            return 0;
            break;
        }

        cursor = cursor -> next;
    }

    return false;
}

加载函数

bool load(const char *dictionary)
{

    FILE *file = fopen(dictionary, "r");

    if (file == NULL)
    {
        printf("error opening file");
        return 1;
    }

    char word [LENGTH + 1];

    while (fscanf(file, "%s\n", word) != EOF)
    {

        int hashInt = hash(word);

        node *n = malloc(sizeof(node));

        if (n == NULL)
        {
            unload();
            return 1;
        }



        if (table[hashInt] == NULL)
        {
            table[hashInt] = n;
        }
        else
        {
            n -> next = table[hashInt];
            table[hashInt] = n;
        }

        strcpy(n -> word, word);
        wordLoaded++;
    }

    fclose(file);

    return true;
}

哈希函数

unsigned int hash(const char *word)
{
    unsigned int hash = 0;

    for (int i = 0, n = strlen(word); i < n; i++)
        hash = (hash << 2) ^ word[i];

    return hash % N;

    return 0;
}

【问题讨论】:

  • hash 函数是否考虑大小写?
  • 不,它没有。我认为。添加了哈希函数。我相信它只是筛选单词并对其进行散列

标签: python-3.x cs50


【解决方案1】:

来自规范:

dictionary 被假定为包含小写列表的文件 单词

您的检查实现必须不区分大小写。

这个int i = strcasecmp(cursor -&gt; word, word); 看起来可以满足要求只要这个int hashInt = hash(word); 也是不区分大小写的。唉,事实并非如此; hash("A") 和 hash("a") 会返回不同的值。

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多