-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagrams.cpp
More file actions
39 lines (35 loc) · 1.22 KB
/
Anagrams.cpp
File metadata and controls
39 lines (35 loc) · 1.22 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
/*
Question:
Anagrams
Asked in:
Amazon
Microsoft
Goldman Sachs
Given an array of strings, return all groups of strings that are anagrams.
Represent a group by a list of integers representing the index in the original list. Look at the sample case for clarification.
Anagram : a word, phrase, or name formed by rearranging the letters of another, such as 'spar', formed from 'rasp'
Note: All inputs will be in lower-case.
Example :
Input : cat dog god tca
Output : [[1, 4], [2, 3]]
cat and tca are anagrams which correspond to index 1 and 4.
dog and god are another set of anagrams which correspond to index 2 and 3.
The indices are 1 based ( the first element has index 1 instead of index 0).
Ordering of the result : You should not change the relative ordering of the words / phrases within the group.
Within a group containing A[i] and A[j], A[i] comes before A[j] if i < j.
*/
vector<vector<int> > Solution::anagrams(const vector<string> &A) {
map<string,vector<int>> m;
for(int i=0;i<A.size();i++)
{
string t=A[i];
sort(t.begin(),t.end());
m[t].push_back(i+1);
}
vector<vector<int>> ret;
for(auto i=m.begin();i!=m.end();i++)
{
ret.push_back(i->second);
}
return ret;
}