标签:
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.
===============
Anagram,相同字母异序词
返回所有的组合
思路:利用hashmap创建一个key-value数据结构,unordered_map<string,int> m;
m的键值是排完序的字符串,value值是vector<vector<string>> re返回值的下标,
这样对于每一个字符串,先对其排序,然后在哈希表中查找,是否有相对应的字符串,
如果有,那么就在re相应位置中插入单词
否则,新建一个字符数组,插入re中.
========
代码:
vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> re; if(strs.empty()) return re; unordered_map<string,int> m; int k = 0; for(size_t i = 0;i<strs.size();i++){ string tmp = strs[i]; sort(tmp.begin(),tmp.end()); unordered_map<string,int>::iterator mit = m.find(tmp); if(mit == m.end()){ vector<string> t; t.push_back(strs[i]); m[tmp] = k++; re.push_back(t); }else{ re[m[tmp]].push_back(strs[i]); } }///for for(size_t i = 0;i<re.size();i++){ sort(re[i].begin(),re[i].end()); } for(auto i:re){ for(auto j:i){ cout<<j<<" "; }cout<<endl; }cout<<endl; return re; }
===========
标签:
原文地址:http://www.cnblogs.com/li-daphne/p/5608360.html