Skip to content

Conversation

@akmhmgc
Copy link
Owner

@akmhmgc akmhmgc commented Sep 27, 2025

解いた問題

139. Word Break

使用言語

Ruby

次に解く問題

322. Coin Change

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

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

Choose a reason for hiding this comment

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

面白いですね。

# @return {Boolean}
def word_break(str, word_dict)
unreachable_suffixes = Set.new
is_reachable = ->(str){

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

word_hashes.add(hash)
end

reachable = Array.bnew(str_size, false)

Choose a reason for hiding this comment

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

Array.new でしょうか。

Copy link
Owner Author

Choose a reason for hiding this comment

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

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


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

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

false
}
is_reachable.call(str)
end

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.

5 participants