标签:
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:
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; } };
标签:
原文地址:http://www.cnblogs.com/zengzy/p/5036982.html