LeetCode OJ-49.Group Anagrams

来源:互联网 发布:汕头有淘宝代运营 编辑:程序博客网 时间:2024/05/22 16:07

LeetCode OJ-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.

Subscribe to see which companies asked this question

题目理解

​ 题目要求将给定的多个字符串中的同字母异序词分组(字母完全相同,只是出现顺序不同),没有太好的办法,暴力求解也是可以过的。先要找出同字母异序词,找出来的关键在于排序后,它们的字母完全相同,以排序后的字符串为key值,所在的组为value值,使用map进行归类就好了。这题主要考察STL中的vector以及map使用是否熟悉了。

​ 注意,在map中查找是否具有相应key时,不能使用std::find,std::find仅支持对迭代器解引用之后是与find的value参数类型相同的情况,对map的迭代器解引用之后,得到的是pair类型,与find传入的value不同类型,不能操作。这里可以使用map实现的find进行操作。

Code

vector<vector<string>> group_anagrams(vector<string> &strs){    vector<vector<string>> res;    map<string, vector<string>> groups;    vector<string> tmp;    string str;    int i;    for (i = 0; i < strs.size(); ++i) {        str = strs[i];        sort(str.begin(), str.end());        if (groups.find(str) == groups.end()) {            tmp.push_back(strs[i]);            groups[str] = tmp;            tmp.clear();  //一定要清空,每次添加分组时,初始分组应该是空的        }        else {            groups[str].push_back(strs[i]);        }    }    map<string, vector<string>>::iterator iter;    for (iter = groups.begin(); iter != groups.end(); ++iter) {        res.push_back((*iter).second);    }    return res;}
0 0
原创粉丝点击