772. Group Anagrams

Code(Language:C++)
class Solution {
public:
    /**
     * @param strs: the given array of strings
     * @return: The anagrams which have been divided into groups
     */
    vector<vector<string>> groupAnagrams(vector<string> &strs) {
        // write your code here
        vector<vector<string>> res; 
        const int size = strs.size();
        if(size == 0){
            return res; 
        }
        unordered_map<string, vector<string>> mp; 
        for(int i = 0; i < size; i++){
            mp[sort(strs[i])].push_back(strs[i]); 
        }
        for(auto i : mp){
            res.push_back(i.second); 
        }
        return res; 
    }
    string sort(string &str){
        vector<int> arr(26, 0);
        for(int i = 0; i < str.size(); i++){
            arr[str[i] - 'a']++; 
        }
        string res = "";
        for(int i = 0; i < 26; i++){
            while(arr[i] > 0){
                res += char('a' + i); 
                arr[i]--; 
            }
        }
        return res; 
    }
};

Comments

Popular posts from this blog

算法的比较