-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanagrams(AC).cpp
More file actions
78 lines (70 loc) · 1.76 KB
/
Copy pathanagrams(AC).cpp
File metadata and controls
78 lines (70 loc) · 1.76 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// 1CE, 1AC
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
typedef struct st{
public:
string str;
string sorted_str;
st(string _str = "", string _sorted_str = "") {
str = _str;
sorted_str = _sorted_str;
}
}st;
bool comparator(const st &x, const st &y)
{
// 1CE here, return a.sorted_str < b.sorted_str;
return x.sorted_str < y.sorted_str;
}
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int max_len = 0;
int i, j, n;
char *ps = nullptr;
result.clear();
v.clear();
n = strs.size();
if(n <= 0){
return result;
}
for(i = 0; i < n; ++i){
if(strs[i].length() > max_len){
max_len = strs[i].length();
}
}
ps = new char[max_len + 1];
string s, ss;
for(i = 0; i < n; ++i){
s = strs[i];
strcpy(ps, s.data());
sort(ps, ps + s.length());
ss = string(ps);
v.push_back(st(s, ss));
}
sort(v.begin(), v.end(), comparator);
delete[] ps;
i = 0;
while(i < n){
j = i;
while(j < n && v[i].sorted_str == v[j].sorted_str){
++j;
}
if(j - i > 1){
while(i < j){
result.push_back(v[i].str);
++i;
}
}
i = j;
}
v.clear();
return result;
}
private:
vector<st> v;
vector<string> result;
};