아주 오랜만에 알고리즘 풀었는데 옛날엔 할 게 많아 하기 싫었는데 그래도 다시 하니 재밌긴 합니다.
unordered_map<int, vector<string>> um; 에서 원소 삽입할 때 키가 없으면std::vector<std::string>을 자동으로 생성한 뒤 참조를 반환함push_back이나 emplace_back 사용 가능for (auto& [key, vec] : um) 으로 하면 key와 value 탐색 가능std::sort는 반환값이 없는 void 함수 → 원본 데이터를 in-place로 수정함class Solution {
public:
static constexpr int M = 20000;
int hash_func(string& str) {
const int a = 1000;
int h = 0;
for (auto& s: str) {
h = (h*a + s) % M;
}
return h % M;
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result;
unordered_map<int, vector<string>> um;
for (auto& str : strs) {
int h = hash_func(str);
um[h].push_back(str);
}
for(auto& [key, vec]: um) {
result.push_back(vec);
}
return result;
}
};
auto hash_func = [M](const string& str) {
const int a = 1000;
int h = 0;
for (auto& s: str) {
h = (h * a + s) % M;
}
return h % M;
};
- 해결2 : 클래스 멤버 함수를 분리
"eat"와 "tea"는 서로 다른 해시값 나옴
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> um;
const int M = 20000;
vector<vector<string>> result;
result.resize(20003);
for (auto& str: strs) {
string s = sort(str.begin(), str.end());
um[s].push_back(str);
}
for (auto& [key, vec] : um) {
result.push_back(vec);
}
return result;
}
};
std::sort는 반환값이 없는 void 함수 → 원본 데이터를 in-place로 수정함class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> um;
const int M = 20000;
vector<vector<string>> result;
for (auto& str: strs) {
string s = str;
sort(s.begin(), s.end());
um[s].push_back(str);
}
for (auto& [key, vec] : um) {
result.push_back(vec);
}
return result;
}
};