leetcode49-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:

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

给出一个字符串数组S,按照同构词(相同字母组成的单词)分类,每类单词按照字典排序。

问题求解:

利用hash表。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        int n=strs.size();
        if(n==0) return vector<vector<string>> ();

        vector<vector<string>> res;
        unordered_map<string, vector<string>> hash;
        //(1)将字符串数组先按字典顺序排序
        sort(strs.begin(), strs.end());
        //(2)构造hash表
        for(int i=0;i<n;i++)
        {//将排序后相等的字符串放在相同的vector
            string tmp=strs[i];
            sort(tmp.begin(), tmp.end());
            hash[tmp].push_back(strs[i]);
        }
        unordered_map<string, vector<string>>::iterator it;
        for(it=hash.begin();it != hash.end();it++)
        {//(3)将hash表中的value值(数组形式)放到结果数组
            res.push_back(it->second);
        }
        return res;
    }
};

你可能感兴趣的:(leetcode49-Group Anagrams(同构词(相同字母组成的单词)分类))