您的位置:首页 > 其它

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:
["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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: