Skip to content

139. Word Break - #34

Open
akmhmgc wants to merge 1 commit into
mainfrom
139
Open

139. Word Break#34
akmhmgc wants to merge 1 commit into
mainfrom
139

Conversation

@akmhmgc

@akmhmgc akmhmgc commented Sep 27, 2025

Copy link
Copy Markdown
Owner

解いた問題

139. Word Break

使用言語

Ruby

次に解く問題

322. Coin Change

@akmhmgc akmhmgc added the ruby label Sep 27, 2025
@akmhmgc akmhmgc self-assigned this Sep 27, 2025
Comment thread 139/step1.md
後から文字列のスライスのコストを考慮してなかったことに気づいた。
文字列のスライスコストを入れるとN * W * (L + N)なのでL * N^2になる。そうなるとRubyでギリギリかもしれないが、LeetCode上では想定以上に速い気がする。

Rubyのスライスメソッドを見たところ、ASCII文字列のスライスはO(1)であるが、マルチバイト文字列のスライスはO(N)らしい。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

面白いですね。

Comment thread 139/step3.md
# @return {Boolean}
def word_break(str, word_dict)
unreachable_suffixes = Set.new
is_reachable = ->(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.

Ruby でどの程度スタイルガイドが参照されているのかわかっていませんが、スタイルガイドでは複数行の場合は lambda を使うのが良いとされていました。
https://github.com/rubocop/ruby-style-guide?tab=readme-ov-file#lambda-multi-line

Comment thread 139/step2.md
word_hashes.add(hash)
end

reachable = Array.bnew(str_size, false)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Array.new でしょうか。

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.

おっしゃる通りです。
コピーする時に誤って入ったのかもしれないです。

Comment thread 139/step2.md

hash = 0
(i...str_size).each do |j|
hash = (hash * base + byte_of.call(str.getbyte(j))) % mod

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この処理はL53にもあるため、関数にしたら良さそうと思いました。

next_rolling_hash = lambda do |hash, c, base, mod|
  (hash * base + byte_of.call(c)) % mod
end

c の型は文字列でも良いかもしれません。

https://discord.com/channels/1084280443945353267/1201211204547383386/1235165575592939521

Comment thread 139/step3.md
false
}
is_reachable.call(str)
end

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

自分は再帰で練習しませんでしたが、変数名含めて読みやすかったです。

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants