forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path249.group-shifted-strings.cpp
More file actions
34 lines (29 loc) · 907 Bytes
/
249.group-shifted-strings.cpp
File metadata and controls
34 lines (29 loc) · 907 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
31
32
33
34
// O(N * K) k = length of string to be shift
class Solution {
private:
// shift str to begin with 'a' for example 'xyz' -> 'abc'
string shiftString(string str){
int offset = 'a' - str[0];
for(int i = 0; i < str.size(); ++i){
str[i] = 'a' + (str[i] + offset - 'a' + 26) % 26;
}
return str;
}
public:
vector<vector<string>> groupStrings(vector<string>& strings) {
unordered_map<string, int> map;
vector<vector<string>> res;
for (auto str: strings){
string tmp = shiftString(str);
if (map.count(tmp) > 0){
res[map[tmp]].push_back(str);
}else{
vector<string> list;
list.push_back(str);
res.push_back(list);
map[tmp] = res.size() - 1;
}
}
return res;
}
};