49. Group Anagrams

来源:互联网 发布:淘宝差评最多的店 编辑:程序博客网 时间:2024/05/01 21:14

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.

  1. All inputs will be in lower-case.
【思路】要求按字母顺序排列,先将字符串sort后,建立map,每个关键词对应的value值为同构的字符串。

<pre name="code" class="cpp">class Solution {public:    vector<vector<string>> groupAnagrams(vector<string>& strs) {        vector<vector<string>> result;        if(strs.empty()) return result;        sort(strs.begin(), strs.end());        map<string, vector<string>> m;        int i = 0;        for(; i < strs.size(); ++i)        {            string s = strs[i];            sort(s.begin(), s.end());            m[s].push_back(strs[i]);        }        map<string, vector<string>>::iterator it = m.begin();        while(it!=m.end())        {            result.push_back(it->second);            ++it;        }        return result;    }};



0 0