leetcode Group Anagrams
2015-12-11 20:20
351 查看
原题链接:https://leetcode.com/problems/anagrams/
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.
以一种奇怪的方式水过去了… (:з」∠)
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> ; 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; };
相关文章推荐
- Imageloader的简单配置
- window.close关闭窗口,不弹出系统提示,直接关闭
- PB中的Describe,Evaluatate,LookUpDisplay小结
- asp.net 导出excel乱码
- IOS核心动画
- VC10中的C++0x特性:Lambdas,auto,以及 static_assert
- 【】
- 阿姆斯特朗数
- NuGet-步步为营,发送类包。
- 上curl java 模拟http请求
- 牛客网练习知识点笔记——Java基础
- 图片焦点轮播效果
- Ten Tips for Writing CS Papers, Part 2
- 【BZOJ 1036】[ZJOI2008]树的统计Count
- leetcode Spiral Matrix
- VMware WorkStation 配置ubuntu 14.4网络(NAT模式)
- linux下进程的实际用户ID(有效组)和有效用户ID(有效组ID)
- Python 一行命令ftp服务器
- Objective-C 面向对象, 实例方法和类方法
- bzoj3997 组合数学 递推