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:
For the return value, each inner list’s elements must follow the lexicographic order.
All inputs will be in lower-case.

解题:
可以先对字符串排序,然后存储到hashmap里面,然后跟剩余的字符(先排序)比对,相等的话则把原串存入到到map中。map

vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> hashMap;
        for(auto &v : strs) {
            string tmp(v);
            sort(tmp.begin(), tmp.end());
            hashMap[tmp].push_back(v);
        }
        vector<vector<string>> result(hashMap.size());
        int k = 0;
        for(auto it = hashMap.begin(); it != hashMap.end(); ++it, ++k) {
            result[k].swap(it->second);
            sort(result[k].begin(), result[k].end());
        }
        return result;
    }

你可能感兴趣的:(LeetCode,C++,算法)