Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
题意
把由相同字母出现相同次数组成的字符串归到一起(数据可能重复)
题解
一开始我当成了任何一种字母只会出现一次做了,用的是long型作二进制用,自然WA了,其实后来可以用字符串做,当时没想到,看了题解有人将字符串排序作为key,觉得挺有道理的
class Solution { public: struct node { string str, after; int idx; node(string a,string b,int id):str(a),after(b),idx(id){} bool operator <(const node&b)const { if (after == b.after) return idx < b.idx; return after < b.after; } }; vector<vector<string>> groupAnagrams(vector<string>& strs) { set<node>all; for (int i = 0; i < strs.size(); i++) { string tmp = strs[i]; sort(strs[i].begin(), strs[i].end()); all.insert(node(tmp, strs[i], i)); strs[i] = tmp; } auto pre = all.begin(); vector<vector<string>>ans; vector<string>tmp; for (auto p = all.begin(); p != all.end(); p++) { if (p != all.begin() && (*p).after != (*pre).after) { ans.push_back(tmp); tmp.clear(); } tmp.push_back((*p).str); pre = p; } ans.push_back(tmp); return ans; } };
顺便放一下用字符串记录字母出现次数做的,比上面那种慢,因为sort还是挺快的
1 class Solution { 2 public: 3 struct node { 4 string str, after; 5 int idx; 6 node(string a,string b,int id):str(a),after(b),idx(id){} 7 bool operator <(const node&b)const { 8 if (after == b.after) 9 return idx < b.idx; 10 return after < b.after; 11 } 12 }; 13 vector<vector<string>> groupAnagrams(vector<string>& strs) { 14 set<node>all; 15 for (int i = 0; i < strs.size(); i++) { 16 string tmp = "00000000000000000000000000"; 17 int l = strs[i].length(); 18 for (int j = 0; j < l; j++) 19 tmp[strs[i][j] - 'a']++; 20 all.insert(node(strs[i], tmp, i)); 21 } 22 auto pre = all.begin(); 23 vector<vector<string>>ans; 24 vector<string>tmp; 25 for (auto p = all.begin(); p != all.end(); p++) { 26 if (p != all.begin() && (*p).after != (*pre).after) { 27 ans.push_back(tmp); 28 tmp.clear(); 29 } 30 tmp.push_back((*p).str); 31 pre = p; 32 } 33 ans.push_back(tmp); 34 return ans; 35 } 36 };