[leetcode_49]Anagrams

给定多个字符串,找出那些Anagrams的字符串组。
Anagrams:eat ate eta
这个题 排序,再排序。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
int cmp(int a, int b) {
    return a < b;
}
struct Item {
    int index;
    string val;
};
int cmpitem(Item a, Item b) {
    return a.val < b.val;
}
class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<Item> strs_cpy;
        strs_cpy.clear();
        for(int i = 0; i < strs.size(); i++) {
            Item item;
            item.index = i;
            item.val = strs[i];
            sort(item.val.begin(), item.val.end(), cmp);
            strs_cpy.push_back(item);
        }
        sort(strs_cpy.begin(), strs_cpy.end(), cmpitem);
        vector<string> ans;
        ans.clear();
        int index = 0;
        for(int i = 1; i < strs_cpy.size(); i++) {
            if(strs_cpy[i].val == strs_cpy[index].val) {
                if(i - index == 1) {
                    ans.push_back(strs[strs_cpy[index].index]);
                }
                ans.push_back(strs[strs_cpy[i].index]);
            } else {
                index = i;
            }
        }
        return ans;
    }
};
Licensed under CC BY-NC-SA 4.0