Group Anagrams
2015-12-10 18:46
387 查看
Total Accepted: 57578 Total Submissions: 226493 Difficulty: Medium
Given an array of strings, group anagrams together.
For example, given:
Return:
Note:
For the return value, each inner list's elements must follow the lexicographic order.
All inputs will be in lower-case.
(E) Valid Anagram (E) Group Shifted Strings
先对每个字符串排序,生成新的串,再对新的串排序,排序好的字符串就是按anagrams规则放在一起
Next challenges: (E) Valid Anagram (E) Group Shifted Strings
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.
(E) Valid Anagram (E) Group Shifted Strings
先对每个字符串排序,生成新的串,再对新的串排序,排序好的字符串就是按anagrams规则放在一起
struct Node{ string origin; string str; Node(string& originValue,string& strValue):origin(originValue),str(strValue){} }; int CompStr(const string& lhs,const string& rhs) { int i=0; while(i<lhs.size() && i<rhs.size()){ if(lhs[i] < rhs[i]){ return 1; }else if(lhs[i] > rhs[i]){ return -1; } i++; } if(i==lhs.size() && i==rhs.size()){ return 0; } return i<rhs.size() ? 1:-1; } bool CompNode(const Node& lhs,const Node& rhs){ int res = CompStr(lhs.str,rhs.str); if(res == 0){ res = CompStr(lhs.origin,rhs.origin); } return res==1 ? true:false; } class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { int strsSize = strs.size(); vector<Node> nodes; for(int i=0;i<strsSize;i++){ string str = strs[i]; sort(str.begin(),str.end()); nodes.push_back(Node(strs[i],str)); } sort(nodes.begin() ,nodes.end(),CompNode); vector<vector<string>> res; vector<string> group; for(int i=0;i<strsSize;i++){ if(i>0 && nodes[i].str!=nodes[i-1].str){ res.push_back(group); group.clear(); } group.push_back(nodes[i].origin); } res.push_back(group); return res; } };
Next challenges: (E) Valid Anagram (E) Group Shifted Strings
相关文章推荐
- java定时任务Timer与ScheduledExecutorService<转>
- iOS多线程 简单实现
- 使用RPM实现LAMP的配置(Wordpress、phpmyadmin)
- nim博弈 hdu3951 Coin Game
- java(7)--客户端上传文本原理
- Android 模糊效果
- Eclipse+Tomcat远程调试配置
- Android下uid与多用户释疑(二)
- Android四大组件之Service详解
- 关于几种排序的个人整理及分析
- bzoj1059(二分图匹配)
- 数据类型问题整理
- Android知识点总结:Android选取、拍照与裁剪图片相关流程分析
- 【Linux】使用DD命令创建文件
- OC .(点)与->(箭头)用法区别
- GCD一次性任务
- hibernate 批量处理数据
- iOS UISlider的使用
- LINUX DIFF命令详解
- 1016.部分A+B