[LeetCode] Group Anagrams

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:

  1. For the return value, each inner list's elements must follow the lexicographic order.
  2. All inputs will be in lower-case.

解題思路:

用hash的方法,將所有的字符分組。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> result;
        
        std::sort(strs.begin(), strs.end());
        
        map<string, vector<string>> codeToStrs;
        for(int i = 0; i<strs.size(); i++){
            codeToStrs[getCode(strs[i])].push_back(strs[i]);
        }
        
        for(map<string, vector<string>>::iterator it = codeToStrs.begin(); it!= codeToStrs.end(); it++){
            result.push_back(it->second);
        }
        
        return result;
    }
    
    string getCode(string s){
        std::sort(s.begin(), s.end());
        return s;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章