先解释一下变位词,变位词就是长度相同,具有相同字母组成的词
比如:sales sales sales sales sales sales sales sales sales sales salse 就是变位词
在介绍程序之前,首先熟悉几个小内容
(1)sort函数
使用sort函数首先要引入algorithm包,默认是升序排序
eg:sort(a,a+n); //a,a+n是数组要排序的起始和终止位置
如果按照自己的意愿来排序的话,就要重写cmp函数:
int cmp( const int &a, const int &b ){
if( a > b )
return 1;
else
return 0;
}
sort(a,a+n,cmp);
是对数组a降序排序
又如:
int cmp( const POINT &a, const POINT &b ){
if( a.x < b.x )
return 1;
else
if( a.x == b.x ){
if( a.y < b.y )
return 1;
else
return 0;
}
else
return 0;
}
sort(a,a+n,cmp);
是先按x升序排序,若x值相等则按y升序排
(2)动态申请数组
以前都是用的malloc现在使用new
string * str = new string[1000];
下面介绍变位词的思想:
(1)为每个单词添加一个标签,标签就是讲每个单词将其字母按照字典序排序,例如 and的标签就是 adn
(2)将标签排序
(3)将具有相同标签的词合并到同一行
实现程序如下:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <algorithm>
using namespace std;
const int num = 120000;
int main()
{
string *szData = new string[num];
char chVal[1000];
string szOld,szNew;
int iCount = 0;
ifstream fInEndic("LDC_DIC.txt");
ofstream fOut("temp.txt");
if(fInEndic.is_open())
{
while(!fInEndic.eof())
{
fInEndic.getline(chVal,1000);
istringstream ss(chVal);
ss>>chVal;
szOld=chVal;
for(int i=0; i<strlen(chVal); i++)
{
if(chVal[i]>=0x41 && chVal[i]<=0x5A)
{//如果是大写字母,转化为小写字母
chVal[i]+=('a'-'A');
}
}
sort(chVal,chVal+strlen(chVal));
//cout<<chVal<<endl;
szNew = chVal;
szData[iCount++] = szNew+" "+szOld;
}
}
sort(szData,szData+iCount);
string szOldData,szNewData;
istringstream ss(szData[0]);
ss>>szOld;
ss>>szOldData;
fOut<<szOldData<<" ";
for(int i=1; i<iCount; i++)
{
istringstream ss1(szData[i]);
ss1>>szNew;
ss1>>szNewData;
if(szOld != szNew)
{
fOut<<endl<<szNewData<<" ";
}
else
{
fOut<<szNewData<<" ";
}
szOld = szNew;
}
fOut.close();
fInEndic.close();
}