Leetcode 49 Anagrams

来源:互联网 发布:淘宝联盟采集器 编辑:程序博客网 时间:2024/05/16 16:18

前几天面试,被面试官问到这个问题,虽然思路说出来了,不过...代码写不出来。为什么?因为对Hash的具体实现不熟悉!上天保佑我过了面试吧。。

回来又练习了一下哈希表的操作。不得不说C++就是强大,比C强多了,尤其是STL。路漫漫啊。

程序的基本思路:首先对给定的每个string排序,然后将排序好的元素作为key,value为元素在原vector中的下标(这样方便以后取数据)。将所有元素放入之后,再次遍历排序好的数组,看看其在hash表中是不是大于一个。如果是,那么取出所有的对应未排序数组的元素,放入返回值中,并且清空该元素对应的哈希表项。


具体实现的时候注意几点:

1. iterator的定义和用法。

2.unordered_multimap中插入元素的方法(要么用pair,要么用{key,value}形式,是initializer。可以参考http://www.cplusplus.com/reference/unordered_map/unordered_multimap/insert/

3.unordered_multimap::count的方法

4.unordered_multimap::equal_range的返回值。程序中用的是auto,实际上应该是pair<unordered_multimap<string, int>::iterator, unordered_multimap<string, int>::iterator> 

5.最后取iterator元素的时候也要注意,取出来的iterator是个key-value 的pair,(*it).first是key,(*it).second是value,别错了。

6.3.unordered_multimap::erase的方法,是删除掉等于相应key的所有value




196ms 过大集合

class Solution{public:vector<string> anagrams(vector<string> &strs){vector<string> ret;if (strs.empty())return ret;vector<string> temp = strs;unordered_multimap<string, int> stringmap; //used to store the stringsunordered_multimap<string, int>::iterator it;//sort each element and add it to the multimapfor (int i = 0; i < temp.size(); i++){sort(temp[i].begin(), temp[i].end());//use the initializerstringmap.insert({temp[i], i});}for (int i = 0; i < temp.size(); i++){if (stringmap.count(temp[i]) > 1){auto range = stringmap.equal_range(temp[i]);for (it = range.first; it != range.second; it++)ret.push_back(strs[(*it).second]);//clear the corresponding elementsstringmap.erase(temp[i]);}elsestringmap.erase(temp[i]);//clear the corresponding elements}return ret;}};


原创粉丝点击