-
Notifications
You must be signed in to change notification settings - Fork 2
/
49.cpp
101 lines (90 loc) · 2.31 KB
/
49.cpp
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Author : Accagain
// Date : 17/3/25
// Email : [email protected]
/***************************************************************************************
*
* 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: All inputs will be in lower-case.
*
* 做法:
* 直接模拟,先排序并记录排序的序号,然后按照顺序输出不同的组
*
* 时间复杂度:
* o(nlg(n))
*
*
****************************************************************************************/
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#define INF 0x3fffffff
using namespace std;
class Solution {
public:
struct Info
{
string str;
int location;
bool operator < (const Info &a) const
{
if(a.str.compare(str)>0)
return true;
return false;
}
Info(string a, int b): str(a), location(b) {}
Info(){}
};
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<Info> now;
for(int i=0; i<strs.size(); i++)
{
string tmp = strs[i];
sort(tmp.begin(), tmp.end());
now.push_back(Info(tmp, i));
}
sort(now.begin(), now.end());
vector<vector<string>> ans;
vector<string> tmp;
string now_str = "";
for(int i=0; i<now.size(); i++)
{
if(now[i].str.compare(now_str))
{
if(!tmp.empty())
ans.push_back(tmp);
tmp.clear();
}
tmp.push_back(strs[now[i].location]);
now_str = now[i].str;
}
if(!tmp.empty())
ans.push_back(tmp);
// for(int i=0; i<ans.size(); i++)
// for(int j=0; j<ans[i].size(); j++)
// printf("%s\n", ans[i][j].c_str());
return ans;
}
};
int main() {
Solution *test = new Solution();
string data[] = {"eat", "eat"};
vector<string> x(data, data + sizeof(data) / sizeof(data[0]));
test->groupAnagrams(x);
return 0;
}
//
// Created by cms on 17/3/25.
//