码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Group Anagrams

时间:2015-08-19 13:33:55      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

Group Anagrams

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.

解题思路:

用hash的方法,将所有的字符分组。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> result;
        
        std::sort(strs.begin(), strs.end());
        
        map<string, vector<string>> codeToStrs;
        for(int i = 0; i<strs.size(); i++){
            codeToStrs[getCode(strs[i])].push_back(strs[i]);
        }
        
        for(map<string, vector<string>>::iterator it = codeToStrs.begin(); it!= codeToStrs.end(); it++){
            result.push_back(it->second);
        }
        
        return result;
    }
    
    string getCode(string s){
        std::sort(s.begin(), s.end());
        return s;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Group Anagrams

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/47777545

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!