Group Anagrams
Total Accepted: 57578 Total Submissions: 226493 Difficulty: Medium
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.
先对每个字符串排序,生成新的串,再对新的串排序,排序好的字符串就是按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
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记