我目前正在通过 odin 项目课程学习 Ruby。这是项目描述:
实现一个方法
#substrings
,将单词作为第一个参数,然后将有效子字符串数组(您的字典)作为第二个参数。它应该返回一个哈希值,列出在原始字符串中找到的每个子字符串(不区分大小写)以及找到的次数。
dictionary = ["below","down","go","going","horn","how","howdy","it","i","low","own","part","partner","sit"]
# => ["below","down","go","going","horn","how","howdy","it","i","low","own","part","partner","sit"]
substrings("below", dictionary)
# => { "below" => 1, "low" => 1 }
substrings("Howdy partner, sit down! How's it going?", dictionary)
# => { "down" => 1, "go" => 1, "going" => 1, "how" => 2, "howdy" => 1, "it" => 2, "i" => 3, "own" => 1, "part" => 1, "partner" => 1, "sit" => 1 }
我首先将字符串转为数组,这样每个单词都是一个数组元素。我循环遍历字典,然后循环遍历字符串数组来比较两个单词,看看它是否包含字典中的子字符串。我使用
string[substring]
检查了子字符串。如果没有返回 nil (意味着字符串包含字典中的子字符串,我会将其推入我的哈希中,创建一个新的键值对。
def substrings(string, dictionary)
result = Hash.new
string_array = string.split" "
dictionary.each do |dic_word|
string_array.each do |string_word|
string_word = string_word.downcase
if string_word[dic_word] != nil
if result.key?(dic_word)
result[dic_word] += 1
else
result[dic_word] = 1
end
end
end
end
result
end
该方法运行良好,我的问题是关于时间复杂度和 Ruby 中的最佳实践。有没有办法提高效率?或者也许有一种方法可以让它看起来更干净,使用其他方法可以更好地解决这个问题。
有关我的代码可读性、变量名称等的任何其他建设性反馈将不胜感激。
我发现 ruby 有一个 #scan 方法,可以提高性能并且不需要新数组
def substrings(string, dictionary)
result = Hash.new
string = string.downcase
dictionary.each do |word|
result[word] = string.scan(word).length unless string.scan(word).length == 0
end
result
end