Conversation
| keyToAnagramGroup := make(map[string][]string, len(strs)) | ||
|
|
||
| for _, str := range strs { | ||
| key := generateKey(str) |
There was a problem hiding this comment.
この関数の括りだし、可読性が上がっていいですね。
左辺と右辺とで情報が増えてないので、例えばこんな命名はどうでしょうか。
| key := generateKey(str) | |
| key := sortedString(str) |
これだと「ソートした文字列をキーにするよ」が分かりやすいのではないでしょうか。
There was a problem hiding this comment.
ありがとうございます。
同じような流れになったので、インターフェース的な発想で抽象度の高い名前になってしまっていました。
状況に応じて適切な命名ができるよう注意します。
| keyToAnagramGroup[key] = append(keyToAnagramGroup[key], str) | ||
| } | ||
|
|
||
| return slices.Collect(maps.Values(keyToAnagramGroup)) |
There was a problem hiding this comment.
こんな便利なメソッドを用意してくれてるんですね。
https://pkg.go.dev/slices#Collect
Goって基本的には「愚直に書け」って言ってくるので感心しました。
There was a problem hiding this comment.
ここ最近で追加されました。
まだあまり使い慣れてないのですが、こういうところで慣れていこうと思っています。
|
|
||
| ```go | ||
| func groupAnagrams(strs []string) [][]string { | ||
| keyToAnagramGroup := make(map[string][]string, len(strs)) |
There was a problem hiding this comment.
[nits]
名前をなるべく短くするGoに従うなら Anagram は削っても良さそうに思いました。Group と言われたら、この関数内では AnagramGroup であることは想像が付くので。
| keyToAnagramGroup := make(map[string][]string, len(strs)) | |
| keyToGroup := make(map[string][]string, len(strs)) |
There was a problem hiding this comment.
そうですね、「伝わるか?」ということを考えてなるべく短い名前を採用するようにします
| for _, str := range strs { | ||
| strBytes := []byte(str) | ||
| slices.Sort(strBytes) | ||
| groups[string(strBytes)] = append(groups[string(strBytes)], str) |
There was a problem hiding this comment.
Go に詳しくないため、理解が間違っていたら申し訳ないです。
ここは破壊的な操作に思われるため、もし入力を変更しなくない場合は、非破壊での操作を検討するのも良いのかなと思いました。
There was a problem hiding this comment.
レビューありがとうございます。
string から []byte へ変換後の Sort していることについてコメントいただいたと考えました。
Go の仕様では string は変更不可能なリソースとなっています。
The Go Programming Language Specification - The Go Programming Language
[]byte(str) で []byte へ型変換すると、新たにメモリが確保されコピーされます。
そのため、上記コードでは入力データは破壊されないようになっています。
The Go Programming Language Specification - The Go Programming Language
改めて公式ドキュメントを確認する機会をいただき、ありがとうございましたmm
今後ともよろしくお願いいたします。
| for _, str := range strs { | ||
| var counts [26]byte | ||
| for i := 0; i < len(str); i++ { | ||
| counts[str[i]-'a']++ | ||
| } |
There was a problem hiding this comment.
leetcode 上ではアルファベットが入力として与えられているため問題になりませんが、アルファベット以外の記号がきた場合には、インデックスがマイナスになる場合が考えられます。これを避けるために、アルファベット以外が来たときは、エラーを投げる、continue する、などの対処法を考えても良さそうです。
There was a problem hiding this comment.
ありがとうございます。
そうですね、実務で想定外の入力を考慮する場合はエラーを返すようにします。
要件次第ですが、下記のようにラベル付き continue を使って、可能な限り処理をすることも選択肢に入れておきます。
OuterLoop:
for _, str := range strs {
var counts [26]byte
for i := 0; i < len(str); i++ {
if str[i] < 'a' || 'z' < str[i] {
continue OuterLoop
}
counts[str[i]-'a']++
}
groups[counts] = append(groups[counts], str)
}
今回の問題
Group Anagrams - LeetCode
使用言語
Go
次に解く問題
Intersection of Two Arrays - LeetCode