寻找字典中变位词

问题

Given a dictionary of English words, return the set of all words grouped into subsets of words that all anagrams of each other.

方案

// FindAnagrams.cpp : Defines the entry point for the console application.
//
#include <vector>
#include <hash_map>
#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <set>

using namespace std;
using namespace stdext;

bool IsAnagrams(string& strA, string& strB)
{
    list<char> listA(strA.begin(), strA.end());
    list<char> listB(strB.begin(), strB.end());

    listA.sort();
    listB.sort();

    return listA == listB;
    // return equal(listA.begin(), listA.end(), listB.begin());
}

string SortChars(string str)
{
    list<char> l(str.begin(), str.end());
    l.sort();
    return string(l.begin(), l.end());
}

set<string> FindAnagrams(list<string>& dict, string findStr)
{
    map<string, set<string>> d;
    typedef pair<string, set<string>> MyPair;

    for(list<string>::const_iterator it = dict.begin(); it != dict.end(); ++it){
        string str(SortChars(*it));

        if(d.find(str) == d.end()){
            set<string> s;
            s.insert(*it);
            d.insert(MyPair(str, s));
        }
        else{
            d[str].insert(*it);
        }
    }

    string sortedStr(SortChars(findStr));

    return d[sortedStr];
}

int main(int argc, char* argv[])
{
    list<string> dict;
    dict.push_back("a");
    dict.push_back("cat");
    dict.push_back("act");
    dict.push_back("tac");
    dict.push_back("foot");
    dict.push_back("toof");
    dict.push_back("room");
    dict.push_back("moor");
    dict.push_back("pitch");
    dict.sort();

    cout << "The dictionary: " << endl;
    copy(dict.begin(), dict.end(), ostream_iterator<string>(cout, ", "));
    cout << endl;

    list<string> testCases;
    testCases.push_back("b");
    testCases.push_back("cat");
    testCases.push_back("room");
    testCases.push_back("hello");
    testCases.push_back("");

    for(list<string>::iterator it = testCases.begin(); it != testCases.end(); ++it)
    {
        cout << endl << "Anagrams of " << *it << " in dictionary" << endl;
        set<string> output = FindAnagrams(dict, *it);
        copy(output.begin(), output.end(), ostream_iterator<string>(cout, ", "));
        cout << endl;
    }

    return 0;
}

输出

The dictionary:
a, act, cat, foot, moor, pitch, room, tac, toof,

Anagrams of b in dictionary


Anagrams of cat in dictionary
act, cat, tac,

Anagrams of room in dictionary
moor, room,

Anagrams of hello in dictionary


Anagrams of  in dictionary

Press any key to continue . . .


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值