gpt4 book ai didi

c - 字谜解算器 C

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

我对 C 完全陌生,所以我在哈希表和链表方面遇到了麻烦。我正在制作一个字谜解算器。我在网上找到了很多例子,但每个人做得都不一样,而且相当复杂,所以我现在很困惑。

我对程序的大部分实现都非常满意。但实际上我一开始就陷入困境。

所以我需要创建一个哈希表,其中每个条目中的键是一个 int,值是一个单词链接列表。

我获取 key 或哈希值的方法是将单词转换为数字。例如,A 为 1,B 为 2,C 为 3,AB 为 3,BC 为 5,ABC 为 6,依此类推。我想这些单词应该不区分大小写,以使事情变得更容易。

下面是我正在编写的代码。我很确定语法不正确。现在我正在研究表格的结构。

typedef struct Entry {
int key;
char *word;
Entry *next;
} Entry;

typedef struct HashTable {
int size;
Entry *entry;
} HashTable;

// initialize table
HashTable* create(int size) {
HashTable *table = (HashTable *)malloc(sizeof(HashTable));
table->entry = (Entry *)malloc(sizeof(Entry) * size);
table->size = size;

int i;
for (i = 0; i < size; i++) {
table->entry[i].key = 0; // All entries to be 0
}

return table;
}

// hash the word
int getHash(char *word)
{
// How do I implement a loop here
}

void insert(HashTable *table, int key, char *word) {
int hash = getHash(word);
int i = 0;

// if key has already existed, find and add to linked list
while(table->entry[hash].key != 0 && (i < table->size)) {
if(table->entry[hash].key == key) {
table->entry[hash].word = word;
return; /* */
}

//hash = (hash + 1); // I'm also stuck with incrementing the hash value
i++; // increment loop index
}

// if key does not exist, find a '0 slot', and store the key and value
if(table->entry[hash].key == 0) {
table->entry[hash].key = key;
table->entry[hash].word = word;
}
}

最佳答案

我建议从一种相当简单的方法开始,从文本中查找单词字谜

int anagrams(char * word, char * text) {
int bin[256] = { 0 }, m = 0, found = 0, len = 0, c, i;
for (i = 0; word[i]; i++, bin[c]--, len++) {
c = word[i];
if(bin[c] == 0) m++;
}
for (i = 0; text[i]; i++) {
c = text[i];
if (bin[c] == 0) m++;
if (bin[c] == -1) m--;
bin[c]++;
if (i >= len) {
c = text[i - len];
if (bin[c] == 0) m++;
if (bin[c] == 1) m--;
bin[c]--;
}
if (m == 0) found++;
}
return found;
}

关于c - 字谜解算器 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31246777/

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