首页 > 其他 > 详细

leetcode Group Anagrams

时间:2015-12-11 22:01:55      阅读:237      评论:0      收藏:0      [点我收藏+]

题目连接

https://leetcode.com/problems/anagrams/  

Group Anagrams

Description

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: 
For the return value, each inner list’s elements must follow the lexicographic order. 
All inputs will be in lower-case. 

以一种奇怪的方式水过去了... __(:з」∠)__

class Solution {
public:
	vector<vector<string>> groupAnagrams(vector<string>& strs) {
		if (!strs.size()) return ans;
		int n = strs.size();
		vector<string> *ret = new vector<string>[n];
		for (int i = 0; i < n; i++) {
			string x = strs[i];
			sort(x.begin(), x.end());
			if (vis.find(x) == vis.end()) { 
				vis[x] = i, index.insert(i);
				ret[i].push_back(strs[i]);
			} else { 
				int v = vis[x];
				vis[strs[i]] = v; 
				ret[v].push_back(strs[i]);
			}
		}
		for (set<int>::iterator i = index.begin(); i != index.end(); ++i) {
			sort(ret[*i].begin(), ret[*i].end());
			ans.push_back(ret[*i]);
		}
		sort(ans.begin(), ans.end(), cmp());
		delete []ret;
		return ans;
	}
private:
	struct cmp {
		bool operator()(const vector<string> &A, const vector<string> &B) {
			int m = (int)A.size(), n = (int)B.size();
			return n == m ? A[0] > B[0] : (bool)(n > m);
		}
	};
	set<int> index;
	unordered_map<string, int> vis;
	vector<vector<string>> ans;
};

leetcode Group Anagrams

原文:http://www.cnblogs.com/GadyPu/p/5040135.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!