-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Valid Anagram #5
Conversation
他の方のPRを見ていて、Goではソートで解く場合、時間計算量は幾つになるのか気になったのでざっくりとですが調べてみました。 |
良さそうに思いました。 |
・文字コードの違いによる実装を考慮できている |
|
||
/* | ||
かなり前に解いたものなので、詳細については忘れてしましました。 | ||
小文字のアルファベットのみが入力として与えられる場合と、Unicode文字も含まれる場合の2つの解法が含まれています。 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
これ、類似の話で他の方にコメントしたときは「日本語はだいたいOK」とふわっとごまかしていたのですが、実はruneにわけると次のような事が起こります。
func main() {
str1 := "ですと"
str2 := "すてど"
fmt.Println(isAnagram_unicode_step1(str1, str2))
str3 := "ですと"
str4 := "すてど"
fmt.Println(isAnagram_unicode_step1(str3, str4))
}
true
false
おそらくtrueになるのは、多くの日本語話者の感覚と反すると思いますし、実際普通の濁音文字ではfalseになりますが、Unicodeでは「"文字面"だけを見るとくっついているのにコードポイントの数は2文字分以上である」という事があります(結合文字)
そのため、runeに分ければ一般にUnicodeでOKかというと、ちょっと難しいところがあります。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
文字コードは魔境で、これ自体は Unicode 正規化で解決しそうですが、訳の分からない非直感的な動作がたくさん起きます。
https://note.com/ttuusskk/n/n1bff5d8e638c
https://note.com/ttuusskk/n/n6f874b0274bd
https://note.com/ttuusskk/n/ne1f4466bb45f
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
なるほど、知りませんでした、、
Valid Anagramを解きました。レビューお願いいたします。
問題セット:Grind75 Easy
言語:Go
問題:https://leetcode.com/problems/valid-anagram/
サロゲートペア・結合文字・合字
Goの内部では常にUTF-8が使用されており、runeはUnicodeコードポイントを表す型で、int32のエイリアスである(https://go.dev/blog/strings )。しかし、Unicodeにはサロゲートペア・結合文字列・合字などがあるため、たとえruneを使ったとしてもそれだけでUnicode文字を完全に適切に処理できるわけではない(参照)。
日本語圏だけでなく、英語圏でも絵文字を使う関係でサロゲートペアの処理は必要である(参照)。
結論としては、文字列にサロゲートペア・結合文字・合字などが含まれる場合であっても、グラフィムクラスタを使えば"≠”のようなリガチャを除けば文字列を前から順に走査するのであれば問題なく文字数をカウントできそう(文字列の途中から走査する場合は旗シーケンスの文字列の場合は文字の境界が判定できないため、結局は文字列の先頭から走査する必要が生じる)。Goの場合、https://pkg.go.dev/golang.org/x/text/unicode/norm を使えばできそう(グラフィムクラスターをGo言語で扱う)。
Unicode
絵文字を支える技術について - note
文字列を反転させたい - note
右から左に書く言語を支える技術