leetcode沒做出來看答案的題

暴露出一個很嚴重的問題就是對stl的應用並不是非常得熟練
49. 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: All inputs will be in lower-case.

Subscribe to see which companies asked this question.

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> group;
        for(const auto& s : strs){
            string key = s;   //strs爲引用,返回結果不需要動strs。所以拷貝下
            sort(key.begin(), key.end());  //用計數排序更優
            group[key].push_back(s);
        }

        vector<vector<string>> res;
        for(auto g : group){
            vector<string> ele(g.second.begin(), g.second.end());
            res.push_back(ele);
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章