网上讲这个问题的blog一大堆,不过我还是按着自己的思路把整个程序实现了一下,还有貌似我的实现方法和大部分讲这个的不一样。
问题引入:
给定一本英语单词词典,找出其中所有的变位词集。例如:因为”pots”,”stop”,”opts”相互之间都是由另一个词的各个字母改变序列实现的,所以这些词之间就是变位词。
常规的解题思路谁都想得出来,不过只要写这样我想肯定就会死的,原因很简单,效率太低。《编程珠玑》上作者给出了一种解法,具体思路是先对输入的单词按照字典顺序进行签名操作,例如把stop,opts,pots,都统一写为:opst,然后通过排序把具有相同签名的单词聚集到一块,最后再将同一个变位词类中的各个单词挤压到一行中打印输出。具体的思路如下图 :
其实在Unix系统中这个程序可以通过管道机制很容易就实现了,不过在这里我给出我自己在windows平台下的实现机制,我自己也不清楚windows有没有管道机制。代码如下:
/*
Problem:anagram
Author:Liang Shaocong
State:Sloved
Date:2015/4/3
*/
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
struct Perals{
std::string sig;
std::string word;
};
bool equal(Perals a,Perals b){
return a.sig<b.sig;
}
int main(void){
std::string sig,word,oldsig="";
std::fstream ivec("word.txt"),write;
write.open("result.txt");
//sign all word
while(ivec>>word){
sig=word;
sort(sig.begin(),sig.end()); //sign by lexicographic order
write<<sig<<" "<<word<<std::endl;
}
//Sort these word
struct Perals wf;
std::vector<Perals> rem;
auto it=rem.begin();
while(write>>sig>>word){
wf.sig=sig,wf.word=word;
rem.push_back(wf);
}
std::cout<<rem.size()<<std::endl;
sort(rem.begin(),rem.end(),equal);
for(it=rem.begin();it!=rem.end();it++)
re<<it->sig<<" "<<it->word<<std::endl;
return 0;
}
挤压程序:
#include <fstream>
#include <iostream>
#include <string>
int main(void){
std::string sig,word,oldsig="";
std::fstream re("rem.txt");
int linenum=0;
while(re>>sig>>word){
if(oldsig!=sig && linenum>0)
std::cout<<std::endl;
oldsig=sig;
linenum++;
std::cout<<word<<" ";
}
std::cout<<std::endl;
return 0;
}
参考资料:《编程珠玑》
http://www.cnblogs.com/solidblog/archive/2012/07/30/2616077.html