Leetcode

Leetcode 49. Group Anagrams

2018-10-12  本文已影响3人  SnailTyan

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

1. Description

Group Anagrams

2. Solution

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;
    }
};
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/
上一篇下一篇

猜你喜欢

热点阅读