leetcode Group Anagrams

题目连接

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;
};
posted @ 2015-12-11 20:21  GadyPu  阅读(227)  评论(0编辑  收藏  举报