“《编程珠玑》(第2版)第2章”:C题(查找变位词,排序)

  C题是这样子的:

  给定一个英语字典,找出其中的所有变位词集合。例如,“pots”、“stop”和“tops”互为变位词,因为每一个单词都可以通过改变其他单词中字母的顺序来得到。

  下段分析摘自该书(P16):

  解决这个问题的许多方法都出奇地低效和复杂。任何一种考虑单词中所有字母的排列的方法都注定了要失败。单词“cholecystoduodenostomy”有22!种排列,少量的乘法运算表明22!约等于1.124*10^21。即使假设以闪电一样的速度百亿分之一秒执行一种排列,这也要消耗1.1*10^9秒。经验法则“pi秒就是一个纳世纪”(见7.1节)指出1.1*10^9秒是数十年。而比较所有单词对的任何方法在我的机器上运行至少要花费一整夜的时间——在我使用的字典里大约230 000个单词,而即使是一个简单的变位词比较也将至少1微秒的时间,因此,总时间估算起来就是:

  230 000单词 * 230 000比较/单词 * 1微秒/比较 = 52 900*10^6微秒=52 900秒,约等于14.7小时。

  对于该问题,上述的方法很明显不可采取的,那有什么更好的方法吗?

  作者在书中提到了一个更为高效的算法:基于排序的标识。这种方法是对单词内的字母进行排序,从而使得同一个变位词类中的单词具有标准型。

  这种方法的核心就在于,对于每一个输入的单词,我们都会对其单词内的字母进行排序,使得其具有一个标准型。如pots,排完序后就是opst。另外,stop、tops的标准型也都是opst,因此可以将这三个单词归类到标准型opst下。适宜实现这种数据结构的是map类型,即关键字“标准型”对应着一堆有相同标准型的单词。至于单词内排序,直接借助sort函数即可。

  下边我个人实现的程序,与作者提供的程序不一样(主要是采用的数据结构不一样):

 1 #include<iostream>
 2 #include <string>
 3 #include <algorithm>
 4 #include <fstream>
 5 #include <map>
 6 #include <vector>
 7 using namespace std;
 8 
 9 int main()
10 {
11     ifstream rfile("words.txt", ios::in);
12     if (!rfile)
13     {
14         cout << "The file can not be opened!" << endl;
15         exit(1);
16     }
17 
18     // core session
19     string line;
20     map<string, vector<string> > seqWords;
21     while (getline(rfile, line))
22     {
23         string tempStr = line;
24         sort(line.begin(), line.end());
25         
26         map<string, vector<string> >::iterator itr = seqWords.find(line);
27         if (itr == seqWords.end())
28         {
29             vector<string> tmpVec;
30             tmpVec.push_back(tempStr);
31             seqWords.insert(pair<string, vector<string> >(line, tmpVec));
32         }
33         else
34         {
35             seqWords[line].push_back(tempStr);
36         }
37     }
38 
39     // print all the elments in seqWords
40     cout << "************************************************" << endl;
41     map<string, vector<string> >::iterator itrMap = seqWords.begin();
42     for (; itrMap != seqWords.end(); itrMap++)
43     {
44         cout << itrMap->first << ": " << endl;
45         vector<string> tempVec = itrMap->second;
46         vector<string>::iterator itrVec = tempVec.begin();
47         for (; itrVec != tempVec.end(); itrVec++)
48         {
49             cout << *itrVec << " ";
50         }
51         cout << endl  << endl;
52     }
53     cout << "************************************************" << endl;
54 
55     return 0;
56 }

  程序输入文件words.txt为:

1 pans
2 pots
3 opt
4 snap
5 stop
6 tops

  程序输出如下:

  

原文地址:https://www.cnblogs.com/xiehongfeng100/p/4375721.html