Leetcode 49 Group Anagrams

2018-01-12 15:07:09 浏览数 (1)

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],  Return:

代码语言:javascript复制
[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note: All inputs will be in lower-case.

将组成字母相同的单词归为一类。

做个简单映射就好了

代码语言:javascript复制
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> result;
        unordered_map<string,int> mp;
        int cnt=0;
        for(int i=0;i<strs.size();i  )
        {
            string temp=strs[i];
            sort(temp.begin(),temp.end());
            if(mp.find(temp)==mp.end())
            {
                vector<string> s;
                s.push_back(strs[i]);
                result.push_back(s);
                mp[temp]=cnt  ;
            }
            else
                result[mp[temp]].push_back(strs[i]);
        }
        return result;
    }
};

0 人点赞