249. Group Shifted Strings
做题历程:
- 本题应该做了不止2次了,本次耗时18分钟,独立解出
本题的难度算是比较低的,我就是在API上耗了一些时间。基本思路就是:
- 写一个计算key的function
- 根据每个string的key,放到hashmap中
- 再把hashmap的value转存到题目需要的
vector<vector<string>>中。
代码如下:
class Solution {
public:
vector<vector<string>> groupStrings(vector<string>& strings) {
unordered_map<string, vector<string>> my_hash_map; // value is index
for (int i = 0; i < strings.size(); ++i) {
string key = getKey(strings[i]);
auto found = my_hash_map.find(key);
if (found == my_hash_map.end()) {
my_hash_map.insert(make_pair(key, vector<string>()));
}
my_hash_map[key].push_back(strings[i]);
}
vector<vector<string>> res;
for (auto it = my_hash_map.begin(); it != my_hash_map.end(); ++it) {
res.push_back(it->second);
}
return res;
}
private:
string getKey(string& str) {
int offset = str[0] - 'a';
string key = "";
for (int i = 0; i < str.length(); ++i) {
if (str[i] < str[0]) {
key += (str[i] + 26 - offset);
}
else {
key += (str[i] - offset);
}
}
return key;
}
};