-
Notifications
You must be signed in to change notification settings - Fork 9
/
Anagrams.cpp
30 lines (24 loc) · 1.4 KB
/
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
/*
Anagrams
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.
*/
//Sort the string and store it in a map of string -> vecotr where vector represents all string at indices i1, i2..
vector<vector<int> > Solution::anagrams(const vector<string> &A) {
unordered_map<string, vector<int> > um;
vector<vector<int> > res;
for(int i=0; i<A.size(); i++){
string temp=A[i];
sort(temp.begin(), temp.end());
um[temp].emplace_back(i+1); // store stringa and vector indices
}
for(auto a = um.begin(); a!=um.end(); a++){
res.emplace_back(a->second); // push vector of indices in res
}
return res;
}