Group Anagrams -- LeetCode

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

 

Note:

  1. For the return value, each inner list's elements must follow the lexicographic order.
  2. All inputs will be in lower-case.

思路:使用哈希表,将每个单词按照其内部字母排序后的结果进行映射。anagram会被映射到同一组中。

 1 class Solution {
 2 public:
 3     vector<vector<string>> groupAnagrams(vector<string>& strs) {
 4         sort(strs.begin(), strs.end());
 5         unordered_map<string, vector<string> > dict;
 6         for (int i = 0, n = strs.size(); i < n; i++)
 7         {
 8             string b = strs[i];
 9             sort(b.begin(), b.end());
10             if (dict.count(b)) dict[b].push_back(strs[i]);
11             else
12             {
13                 vector<string> tem(1, strs[i]);
14                 dict.insert(make_pair(b, tem));
15             }
16         }
17         vector<vector<string> > res;
18         for (auto i : dict)
19             res.push_back(i.second);
20         return res;
21     }
22 };

 

posted @ 2016-01-27 12:08  fenshen371  阅读(153)  评论(0编辑  收藏  举报