-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathGroup_Shifted_Strings.cpp
More file actions
30 lines (30 loc) · 945 Bytes
/
Group_Shifted_Strings.cpp
File metadata and controls
30 lines (30 loc) · 945 Bytes
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
class Solution {
public:
string getHash(string key) {
string hash = "#";
for(int i = 1; i < key.length(); ++i) {
int diff = ((key[i] - key[i -1]) + 26) % 26;
hash += to_string(diff);
hash += '#';
}
return hash;
}
vector<vector<string>> groupStrings(vector<string>& strings) {
vector<vector<string>> result;
unordered_map <string, vector<string>> hashMap;
for(string s: strings) {
string key = getHash(s);
if(hashMap.find(key) != hashMap.end()) {
hashMap[key].push_back(s);
} else {
vector<string> grp{s};
hashMap[key] = grp;
}
}
for(auto it = hashMap.begin(); it != hashMap.end(); ++it) {
sort(it->second.begin(), it->second.end());
result.push_back(it->second);
}
return result;
}
};