在单词列表中查找字谜

时间:2011-06-21 08:48:59

标签: c++ anagram

我有一个单词列表和一个包含许多字谜的文件。这些字谜是单词列表中的单词。我需要开发一种算法来查找匹配的单词并在输出文件中生成它们。到目前为止我开发的代码只适用于前两个单词。另外,我无法让代码与包含数字的字符串一起玩得很好。请告诉我如何修复代码。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main (void)
{
int x = 0, y = 0;
int a = 0, b = 0;
int emptyx, emptyy;
int match = 0;
ifstream f1, f2;
ofstream f3;
string line, line1[1500], line2[50];
size_t found;

f1.open ("wordlist.txt");
f2.open ("file.txt");
f3.open ("output.txt");

while (f1.eof() == 0)
{
    getline (f1, line);
    line1[x] = line;
    x++;
}

while (f2.eof() == 0)
{
    getline (f2, line);
    line2[y] = line;
    y++;
}

//finds position of last elements
emptyx = x-1;
emptyy = y-1;

//matching algorithm
for (y = 0; y <= emptyy; y++)
{
    for (x = 0; x <= emptyx; x++)
    {
        if (line2[y].length() == line1[x].length())
        {
            for (a = 0; a < line1[x].length(); a++)
            {
                found = line2[y].find(line1[x][a]);
                if (found != string::npos)
                {
                    match++;
                    line2[y].replace(found, 1, 1, '.');

                    if (match == line1[x].length())
                    {
                        f3 << line1[x] << ", ";
                        match = 0;
                    }
                }
            }
        }
    }
}

f1.close();
f2.close();
f3.close();

return 0;
}

2 个答案:

答案 0 :(得分:6)

步骤1:使用词汇表中每个单词中已排序字符的键构建索引,其值为单词。

act   -  cat
act   -  act
dgo   -  dog

...

aeeilnppp - pineapple

....

etc...

步骤2:对于您要查找的每个字谜,对字谜词中的字符进行排序,然后与索引匹配,以从匹配排序键的索引中检索所有单词。

答案 1 :(得分:3)

试图改善Mitch Wheat的解决方案:

  • 存储排序顺序和单词实际上不是必需的 - 只存储列表中每个单词的排序字符串。

  • 无论如何,当我们从文件中读取一个单词时,我们必须对它进行排序以查找它是否等于排序的字符串 - 并且索引是在已排序的字符串上编制索引的,所以它无论如何都无济于事。 p>

  1. 使用单词列表中的单词构建“位置无关”哈希 - 还将已排序的字符串存储在哈希中。

  2. 对于文件中的每个单词,获取“位置无关”哈希并检入哈希表。

  3. 如果点击,排序并与哈希(碰撞!)中存储在此位置的每个排序字符串进行比较。

  4. 思想?