【问题标题】:Anagram Solver C字谜解算器 C
【发布时间】:2015-09-23 15:42:51
【问题描述】:

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

该程序的大部分实施我都很好。但实际上我一开始就被卡住了。

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

我获取密钥或哈希值的方法是将单词转换为数字。例如,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;
   }
}

【问题讨论】:

标签: c linked-list hashtable anagram


【解决方案1】:

我建议从一个相当简单的方法开始,从text 中找到word 中的anagrams

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;
}

【讨论】:

    猜你喜欢
    • 2015-10-31
    • 2014-05-09
    • 2021-09-13
    • 2012-11-03
    • 2011-11-03
    • 2012-03-17
    • 2011-11-02
    • 2011-01-17
    • 2019-07-10
    相关资源
    最近更新 更多