难度中等207收藏分享切换为英文关注
通过次数
35,503
提交次数
59,957
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
好久没有一次过了。思路非常简单,一个字符串ascall码排序
和unorder_map的两层映射去重!渣渣用的排序是冒泡排序.....
#include <iostream>
#include <vector>
#include <algorithm>
#include <string.h>
#include <unordered_map>
using namespace std;
/* 建立两层映射关系 */
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<string> strList;
vector<string>::iterator it = strs.begin();
while(it!=strs.end()){
string temp = GetSort(*it);
m_map[temp].push_back(*it);
/* 去重 */
if(m_count.count(temp)==0){
m_count[temp] = temp;
strList.push_back(temp);
}
it++;
}
vector<vector<string>> res;
vector<string>::iterator VecTemp = strList.begin();
while(VecTemp!=strList.end()){
// cout<<"VecTemp:"<<(*VecTemp)<<endl;
res.push_back(m_map[*VecTemp]);
VecTemp++;
}
return res;
}
private:
unordered_map<string,vector<string>> m_map;
unordered_map<string,string> m_count;
string GetSort(string value);
};
/* 判断是否为相同字符串 */
string Solution::GetSort(string value){
string res;
char dest[256] = {'\0'};
int len = value.length();
strcpy(dest,value.c_str());
for(int i=0;i<len-1;i++){
for(int j=0;j<len-i-1;j++){
if(dest[j]>dest[j+1]){
char temp = dest[j];
dest[j] = dest[j+1];
dest[j+1] = temp;
}
}
}
res = dest;
cout<<"dest:"<<res<<endl;
return res;
}
int main(){
vector<string> Vec = {"eat", "tea", "tan", "ate", "nat", "bat"};
Solution *ps = new Solution();
vector<vector<string>> res = ps->groupAnagrams(Vec);
vector<vector<string>>::iterator it = res.begin();
while(it!=res.end()){
vector<string>::iterator base = (*it).begin();
cout<<"list:";
while(base!=((*it).end())){
cout<<*base<<" ";
base++;
}
cout<<endl;
it++;
}
return 0;
}