生成字符串的所有可能的连续单词组合

Generate all possible consecutive word combinations of a string

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

假设我有 "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

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

此解决方案避免了不必要的 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