Programming Perals 变位词实现

网上讲这个问题的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值