c - 字谜解算器 C

标签 c linked-list hashtable anagram

我对 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/

相关文章:

C++ 为 POD 对象赋值

c# - 快速访问文件中的 key (无需将整个文件加载到内存中)

Java - 具体的链表序列化

java - 为什么我的反向链表方法不能多次工作?

c - C中的重新散列函数

java - Hashtable 查询的 J2ME Vector

c - 读取一个 32 位整数的第 31 位的值

c - 开始学习c但不知道为什么要用Return 0

c - 当指针指向使用 malloc() 获得的内存位置时,编译器如何处理 CONST 限定符?

linked-list - 从单向链表中删除节点出现错误 "cannot move out of borrowed content"