美文网首页Leetcode
Leetcode 49. Group Anagrams

Leetcode 49. Group Anagrams

作者: SnailTyan | 来源:发表于2018-10-12 19:08 被阅读3次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Group Anagrams

    2. Solution

    • Version 1
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>> result;
            unordered_map<string, vector<string>> m;
            for(string s : strs) {
                string temp = s;
                sort(temp.begin(), temp.end());
                if(m.find(temp) != m.end()) {
                    m[temp].push_back(s);
                }
                else {
                    vector<string> anagrams;
                    anagrams.push_back(s);
                    m[temp] = anagrams;
                }
            }
            for(auto iter: m) {
                result.push_back(iter.second);
            }
            return result;
        }
    };
    
    • Version 2
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>> result;
            unordered_map<string, vector<string>> m;
            for(string s : strs) {
                string temp = s;
                sort(temp.begin(), temp.end());
                m[temp].push_back(s);
            }
            for(auto iter: m) {
                result.push_back(iter.second);
            }
            return result;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/group-anagrams/description/

    相关文章

      网友评论

        本文标题:Leetcode 49. Group Anagrams

        本文链接:https://www.haomeiwen.com/subject/wbngaftx.html