1. 程式人生 > >19.2.7 [LeetCode 49] Group Anagrams

19.2.7 [LeetCode 49] Group Anagrams

tmp ins length 排序 opera operator 相同 開始 truct

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; } };
View Code

順便放一下用字符串記錄字母出現次數做的,比上面那種慢,因為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 };
View Code

19.2.7 [LeetCode 49] Group Anagrams