Skip to content

49. Group Anagrams#12

Open
n6o wants to merge 1 commit intomainfrom
group-anagrams
Open

49. Group Anagrams#12
n6o wants to merge 1 commit intomainfrom
group-anagrams

Conversation

@n6o
Copy link
Copy Markdown
Owner

@n6o n6o commented Feb 9, 2026

今回の問題

Group Anagrams - LeetCode

使用言語

Go

次に解く問題

Intersection of Two Arrays - LeetCode

keyToAnagramGroup := make(map[string][]string, len(strs))

for _, str := range strs {
key := generateKey(str)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

この関数の括りだし、可読性が上がっていいですね。
左辺と右辺とで情報が増えてないので、例えばこんな命名はどうでしょうか。

Suggested change
key := generateKey(str)
key := sortedString(str)

これだと「ソートした文字列をキーにするよ」が分かりやすいのではないでしょうか。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。
同じような流れになったので、インターフェース的な発想で抽象度の高い名前になってしまっていました。
状況に応じて適切な命名ができるよう注意します。

keyToAnagramGroup[key] = append(keyToAnagramGroup[key], str)
}

return slices.Collect(maps.Values(keyToAnagramGroup))
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

こんな便利なメソッドを用意してくれてるんですね。
https://pkg.go.dev/slices#Collect

Goって基本的には「愚直に書け」って言ってくるので感心しました。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここ最近で追加されました。
まだあまり使い慣れてないのですが、こういうところで慣れていこうと思っています。


```go
func groupAnagrams(strs []string) [][]string {
keyToAnagramGroup := make(map[string][]string, len(strs))
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nits]
名前をなるべく短くするGoに従うなら Anagram は削っても良さそうに思いました。Group と言われたら、この関数内では AnagramGroup であることは想像が付くので。

Suggested change
keyToAnagramGroup := make(map[string][]string, len(strs))
keyToGroup := make(map[string][]string, len(strs))

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

そうですね、「伝わるか?」ということを考えてなるべく短い名前を採用するようにします

for _, str := range strs {
strBytes := []byte(str)
slices.Sort(strBytes)
groups[string(strBytes)] = append(groups[string(strBytes)], str)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Go に詳しくないため、理解が間違っていたら申し訳ないです。
ここは破壊的な操作に思われるため、もし入力を変更しなくない場合は、非破壊での操作を検討するのも良いのかなと思いました。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

レビューありがとうございます。

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
今後ともよろしくお願いいたします。

Comment on lines +73 to +77
for _, str := range strs {
var counts [26]byte
for i := 0; i < len(str); i++ {
counts[str[i]-'a']++
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

leetcode 上ではアルファベットが入力として与えられているため問題になりませんが、アルファベット以外の記号がきた場合には、インデックスがマイナスになる場合が考えられます。これを避けるために、アルファベット以外が来たときは、エラーを投げる、continue する、などの対処法を考えても良さそうです。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。

そうですね、実務で想定外の入力を考慮する場合はエラーを返すようにします。
要件次第ですが、下記のようにラベル付き 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)
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants