#include <iostream>
#include <stdio.h>
#include <vector>
#include <map>
#include <algorithm>
#include <string>
using namespace std;
/*
问题:
Total Accepted: 114812
Total Submissions: 355832
Difficulty: Medium
Contributors: Admin
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.
分析:
anagrams:颠倒字母顺序构成的字
这是程序员面试金典的一道题目。需要对每个字符串排序。
设定一个map<string,vector<string>>,键是:颠倒字符串中最小的字符串,值是对应的字符串
输入:
6(字符串个数)
eat tea tan ate nat bat
输出:
ate eat tea, nat, tab bat
*/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> results;
if(strs.empty())
{
return results;
}
map<string , vector<string> > strToResults;
int size = strs.size();
string value;
for(int i = 0 ; i < size ; i++)
{
value = strs.at(i);
sort(value.begin() , value.end());
if(strToResults.find(value) != strToResults.end())
{
strToResults[value].push_back(strs.at(i));
}
else
{
vector<string> result(1 , strs.at(i));
strToResults[value] = result;
}
}
//输出最终结果
for(map<string , vector<string> >::iterator it = strToResults.begin() ; it != strToResults.end() ; it++)
{
results.push_back(it->second);
}
return results;
}
};
void print(vector< vector<string> >& results)
{
if(results.empty())
{
cout << "no result" << endl;
return ;
}
int size = results.size();
int len;
for(int i = 0 ; i < size ; i++)
{
len = results.at(i).size();
for(int j = 0 ; j < len ; j++)
{
cout << results.at(i).at(j) << " ";
}
cout << "," ;
}
}
void process()
{
int num;
string value;
vector<string> strs;
Solution solution;
vector< vector<string> > results;
while(cin >> num)
{
strs.clear();
for(int i = 0 ; i < num ; i++)
{
cin >> value;
strs.push_back(value);
}
results = solution.groupAnagrams(strs);
print(results);
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:49. Group Anagrams
最新推荐文章于 2021-09-24 19:27:23 发布