use map<key, val> in C++, solve LeetCode Anagrams 240 ms pass large test set

3 篇文章 0 订阅
2 篇文章 0 订阅

Anagrams

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

The basic idea is easy.  From the definition of anagrams, we just need to get the histogram of each string.  Then we just need to figure out if two string has the same histogram.


To calculate if two strings have the same histogram, we could use hashtable to do O(1) comparison, or use tree structure to do O(logN)


Now let's suppose we use the map in C++ STL to do O(logN) to compare the key.  The key is actually an array of 26 numbers (each number indicate how many times a word appears in the string).  To use map, we need to create a comparison method, we could do


class HistKey{

};


class MyComp{

    bool operator(const HistKey &a, const HistKey &b){

        //if a < b, return true;

        //else return false; ********************* It is very important here that we need to return false if a==b

    }

};


we could create the map by

map<HistKey, pair<string, bool>> histogram


To find if two histogram is the same for two strings, we could just do:

histogram.find(a_hist) != histogram.end()


Note, it is important that if two key are the same, it need to return false in MyComp


My code could pass the result within 240 ms.  Please let me know if you would like to see the code


Reference:

Map以自定义类做为键值


http://www.seacha.com/article.php/knowledge/cbase/2011/1020/1859.html


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值