在单词表中查找变位词
Finding anagrams in a word list
我有一个单词列表和一个包含许多变位词的文件。这些字谜是单词表中的单词。我需要开发一种算法来找到匹配的单词,并在输出文件中生成它们。到目前为止,我开发的代码只适用于前两个单词。此外,我无法让代码在任何地方都能很好地处理包含数字的字符串。请告诉我如何修复代码。
#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;
}
步骤1:用单词列表中每个单词中已排序字符的键构建索引,并将值作为单词。
act - cat
act - act
dgo - dog
...
aeeilnppp - pineapple
....
etc...
步骤2:对于你想找到的每个变位词,对变位词中的字符进行排序,然后与索引匹配,用匹配的排序键从索引中检索所有单词。
尝试改进Mitch小麦的解决方案:
-
存储排序顺序和单词实际上是不必要的——只存储列表中每个单词的排序字符串。
-
无论如何,当我们从文件中读取一个单词时,我们必须对其进行排序,以确定它是否等于已排序的字符串——并且索引是在已排序的串上索引的,所以这无论如何都没有帮助。
-
使用单词列表中的单词构建一个"位置独立"哈希,并将排序后的字符串存储在哈希中。
-
对于文件中的每个单词,获取"位置无关"哈希并签入哈希表。
-
如果命中,则对哈希中存储在该位置的每个已排序字符串进行排序和比较(碰撞!)。
想法?
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- QTreeView幻灯片多选后无法使用单击选择
- 查找最接近的大于当前数字的数字的索引
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 查找后更改类变量
- 使用正则表达式regex_search在字符串中查找字符串
- 使用gcc从静态链接的文件中查找可选符号
- 在C++中查找范围的长度
- 算法问题:查找从堆栈中弹出的所有序列
- 使用 SFML 在矩形的矢量中查找鼠标单击量
- OpenCV CV 查找单应断言错误计数器 = > 4
- C++ 查找其中字母最少的单词数
- 在GDB(C++)中查找指向单例死后的指针
- 如何通过检查v. dictionary来查找一个短语中删除空格的单词数
- 在 WindowProc 中查找按钮单击事件的原因
- 为什么查找字符串的方法比我的单遍快
- 在单词表中查找变位词