Conversation
| for (string str : strs) { | ||
| string _string = str; |
There was a problem hiding this comment.
これは二回コピーしていますね。push_back する方は参照でもいいはずです。
あまり大きな問題ではないですが、一応。
つまり、const string& str: strs としてこちらを push_back する手があります。
There was a problem hiding this comment.
ありがとうございます。
たしかに、
for (const string& str : strs) {
string _string = str;
でよかったですね。
| for (string str : strs) { | ||
| string _string = str; |
There was a problem hiding this comment.
ローカル変数の場合 _ から変数名をはじめるのは言語仕様上問題はないのですが、スタイルでしないようにしていることもあるかと思います。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.yekt5frcrx1o
https://discord.com/channels/1084280443945353267/1367399154200088626/1405160975677788201
There was a problem hiding this comment.
補足します。
二重アンダースコア__ を含む識別子 、またはアンダースコアで始まり大文字が続く 識別子は、実装での使用のために予約されています。使用しないでください。
https://timsong-cpp.github.io/cppwp/n4950/lex.name#3.1
Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.
| string key(26, '\0'); | ||
| for (char character : _string) { | ||
| key[character - 'a']++; | ||
| } |
There was a problem hiding this comment.
長さ26の文字列のバッファを作り、文字コードをカウンターとして使うということですね。
自分はC++に疎く、それを読解するのに少々苦戦しました。
次に、char型は1バイトであり、signed charなら-128 〜 127、unsigned charなら0 〜 255の値域のため、この方法で同じ文字が128 or 256回以上登場するとオーバーフロー(ここでは循環)して128 or 256の倍数の差が同一視される危険があるのではないでしょうか。
本問の入力制約ではstrs[i]の長さは100以下とのことで一応問題ないですが、将来的なスケーリングや堅牢性を考えて個人的に不安を感じました。
unhashableですがvector<int>でまず数え、その後hashableにする方針の方が安全かつ読みやすいと感じます。例えば[1, 0, 2, ...] → "1,0,2,..." や "a1b0c2..."など。
There was a problem hiding this comment.
char型のオーバーフローの可能性にも文字列のサイズが100までであることにも全く気付いていなかったです。(コード自体はIwaseさんのコードをGPTにC++に変換してもらったものでした)ご指摘ありがとうございます。
この問題:https://leetcode.com/problems/group-anagrams/description/
次に解く問題:https://leetcode.com/problems/intersection-of-two-arrays/description/