leecode 解题总结:49. Group Anagrams

#include 
#include 
#include 
#include 
#include 
#include 

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>,键是:颠倒字符串中最小的字符串,值是对应的字符串

输入:
6(字符串个数)
eat tea tan ate nat bat
输出:
ate eat tea, nat, tab bat
*/

class Solution {
public:
    vector> groupAnagrams(vector& strs) {
		vector> results;
        if(strs.empty())
		{
			return results;
		}
		map > 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 result(1 , strs.at(i));
				strToResults[value] = result;
			}
		}
		//输出最终结果
		for(map >::iterator it = strToResults.begin() ; it != strToResults.end() ; it++)
		{
			results.push_back(it->second);
		}
		return results;
    }
};

void print(vector< vector >& 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 strs;
	Solution solution;
	vector< vector > 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)