【问题标题】:Generate all possible consecutive word combinations of a string生成字符串的所有可能的连续单词组合
【发布时间】:2017-01-07 17:10:41
【问题描述】:

我想生成特定字符串的所有可能的连续单词组合,给定最小长度作为 arg。

假设我有“hello”,结果将是(给定最小长度为 3):'hel'、'ell'、'llo'、'hell'、'ello'、'hello'。

我实现这一目标的一种方法是:

def get_all_word_combinations(str, min_length)
    chars = str.split('')
    all_results = []

    (min_length..str.size).each do |x|
      chars.each_cons(x) do |r|
        all_results << r.join
      end
    end
    return all_results
  end

但不确定这是否适用于更大的单词。

【问题讨论】:

  • @Carcigenicate 抱歉,问题更多是关于问题的正确性。已编辑。
  • 换个问题:为什么不能处理更大的单词?代码中的什么取决于字长?也就是说,要求并不明确。 “hel”和“leh”有区别吗?
  • 这里看不出什么问题...也许get_all_word_slices 是一个更好的名字。
  • 当你用更大的词尝试它时发生了什么?
  • 这与stackoverflow.com/questions/41521492/… 有关吗?我不确定你真的需要所有这些子字符串

标签: ruby string combinations words


【解决方案1】:

这个解决方案避免了不必要的joins

word     = "hello"
size     = word.size
min_size = 3

(min_size..size).flat_map { |l| (0..size - l).map { |i| word[i, l] } }
#=> ["hel", "ell", "llo", "hell", "ello", "hello"]

如果您不需要数组,而只需要遍历每个可能的子字符串,则此解决方案将使用更少的内存:

(min_size..size).each do |l|
  (0..size - l).each do |i|
    # do something with word[i, l]
  end
end

【讨论】:

  • 考虑到word = "aaaa"; size = word.size; min_size = 2; (min_size..size).flat_map { |l| (0..size - l).map { |i| word[i, l] } } #=&gt; ["aa", "aa", "aa", "aaa", "aaa", "aaaa"],我建议你添加.uniq
  • @CarySwoveland :我想这真的取决于数组的大小和 OP 的意图。在一个巨大的数组上使用 uniq 来删除一些子字符串可能不值得。使用each 两次可能是一个更好的主意。
  • 一种选择是从字面上解释这个问题:“我想生成特定字符串的所有可能的连续单词组合......”。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
  • 2022-08-24
  • 1970-01-01
  • 2021-12-14
  • 2012-03-03
相关资源
最近更新 更多