[leetcode] 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.

解法一:

首先把有序的string排序,作爲hash table的key,然後把anagrams在結果中的存儲index作爲每一個bucket的key。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        
        unordered_map<string, int> m;
        
        int idx = 0;
        for(int i=0; i<strs.size(); i++){
            string s = strs[i];
            sort(s.begin(),s.end());
            if(m.find(s)==m.end()){
                vector<string> tmp(1,strs[i]);
                res.push_back(tmp);
                m[s] = idx;
                idx++;
            }else{
                res[m[s]].push_back(strs[i]);
            }
        }
        return res;
    }
};


發佈了31 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章