您的位置:首页 > 编程语言 > C语言/C++

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

2013-04-21 16:22 531 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 C++ STL map