Conversation
Added detailed explanation and example code for grouping anagrams.
|
|
||
| class Solution { | ||
| public: | ||
| std::vector<std::vector<std::string> > groupAnagrams(std::vector<std::string>& strs) { |
There was a problem hiding this comment.
C++11 以降 > と > のあいだにスペースを空けなくて済むようになっています。スペースを消すことをおすすめします。
https://cpprefjp.github.io/lang/cpp11/right_angle_brackets.html
C++11からは、 vector<basic_string> のように、2つ以上連続する右山カッコの間に、スペースを入力する必要がなくなった。
| public: | ||
| std::vector<std::vector<std::string> > groupAnagrams(std::vector<std::string>& strs) { | ||
| std::unordered_map<std::string, std::vector<std::string> > groups; | ||
| for (const std::string& s : strs) { |
There was a problem hiding this comment.
for (const auto& s : strs) {のほうがシンプルだと思います。
There was a problem hiding this comment.
@nodchip
ご指摘ありがとうございます。
こちらの方が明示的かと思いましたが、これくらいであれば
for (const auto& s : strs) {
の方が読みやすいかもしれないですね。
ありがとうございます。
| } | ||
|
|
||
| std::vector<std::vector<std::string> > result; | ||
| result.reserve(groups.size()); |
There was a problem hiding this comment.
reserve() をすることにより、あらかじめ必要な要素数分のメモリを確保し、 push_back() 中のメモリの再確保を避けることができるのですが、その効果が十分かどうかは計測してみないと何とも言えません。処理時間に対する要求を考慮し、シビアでない場合、 コードをシンプルにするため、reserve() を呼び出さないほうがよい場合もあると思います。
There was a problem hiding this comment.
@nodchip
ありがとうございます。
効果の測定まで検証できておりませんでした。chronoで時間を測ってみたいと思います。
|
全体的に読みやすいと思います。 |
|
全体として読みやすかったです. |
|
|
||
| class Solution { | ||
| public: | ||
| std::vector<std::vector<std::string> > groupAnagrams(std::vector<std::string>& strs) { |
There was a problem hiding this comment.
非const参照で受け取ると変更の可能性があることを呼び出し側は考慮することになるので、内部で変更をしないのであればconstをつけてもよいかと思います。
| for (const std::string& word : strs) { | ||
| std::string key = word; | ||
| std::sort(key.begin(), key.end()); | ||
| groups[key].push_back(s); |
| class Solution { | ||
| public: | ||
| std::vector<std::vector<std::string> > groupAnagrams(std::vector<std::string>& strs) { | ||
| std::unordered_map<std::string, std::vector<std::string> > groups; |
There was a problem hiding this comment.
なにをキーにしてグループをまとめているかの情報が後を読まないとわからないので、sorted_str_to_groups(sorted_str_to_anagramsなど)くらいでもよいかなと思いました。
This : https://leetcode.com/problems/group-anagrams/
Next: https://leetcode.com/problems/intersection-of-two-arrays/description/