LeetCode 49. Group Anagrams HashTable

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Note:
  • All inputs will be in lowercase.
  • The order of your output does not matter.

解法:

  首先遍历输入,同时对每个string按 字典序 排序;(为了使相同字母异构 经hashtable映射得到相同的值)

  排序后相同的value 进入同一个字符数组

     核心在于排序

class Solution {
public:

    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string,vector<string>> m;
        vector<vector<string>> res;
        for(int i = 0; i < strs.size(); i++){
            string s = strs[i];
            sort(s.begin(),s.end());// 先对每个字符串排序
            m[s].push_back(strs[i]); // 相同字母异构的字符串 经排序后  原来的异构字符串被 映射到一个同一个位置,
            //并用string存储原来的值
        }
        
        for(auto ss : m){
            vector<string> level = ss.second;
            res.push_back(level);
        }
        return res;
    }
};

 

posted @ 2019-09-23 11:14  3/8  阅读(88)  评论(0编辑  收藏  举报