-
Notifications
You must be signed in to change notification settings - Fork 0
/
49. Group Anagrams.cpp
57 lines (54 loc) · 1.69 KB
/
49. Group Anagrams.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
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> toreturn;
if(strs.size()==1)
{
toreturn.push_back({strs[0]});
return toreturn;
}
int n = strs.size();
vector<bool> visited(n,false);
for(int i = 0;i<n;i++)
{
if(!visited[i])
{
visited[i]=true;
string temp = strs[i];
sort(temp.begin(),temp.end());
vector<string> v;
v.push_back(strs[i]);
for(int j = 0;j<n;j++)
{
if(!visited[j])
{
if(strs[j].length()==temp.length())
{
bool flag = true;
string temp1 = strs[j];
sort(temp1.begin(),temp1.end());
for(int k = 0;k<temp.length();k++)
{
if(temp[k]!=temp1[k])
{
flag = false;
}
}
if(flag)
{
v.push_back(strs[j]);
visited[j] = true;
}
}
else
{
continue;
}
}
}
toreturn.push_back(v);
}
}
return toreturn;
}
};