字符串中子串的组合

时间:2011-05-06 20:50:22

标签: ruby combinations

如何找到给定字符串中一组字符串的所有可能组合?

strings = ["ab","aa","ab","bb","ba","aba","aab"]
given_string = "abaababbab"

必须返回:

[
 ["ab","aa","ba","bb","ab],
 ["ab","aab","ab","ba","bab"]
 ["aba","aba","bb","ab"]
] 

2 个答案:

答案 0 :(得分:1)

粗略的想法可能是这样的:

strings.select do |s|
  given_string.index(s)
end

这会给你:

["ab", "aa", "ab", "bb", "ba", "aba", "aab"]

我不确定你是否在这里寻找重复。如果你不小心,你最终可能会遇到一个计算复杂的问题,因为这种事情使得DNA测序的计算密集程度非常高。

答案 1 :(得分:-1)

以下内容:

strings = ["ab","aa","ab","bb","ba","aba","aab"]
@strings = strings.uniq!
@given_string = 'abaababbab'
@given_length = @given_string.length

def parse
  @parses.each do |parse|
    before = parse.pop # offset of the part that hasn't yet been parsed
    @strings.each do |str|
      next unless m = @given_string.match(str, before)
      first, last = m.offset(0)
      next unless first == before
      if last == @given_length
        @completed_parses.push([*parse, str])
      else
        @new_parses.push([*parse, str, last])
      end
    end
  end
  @parses = @new_parses
  @new_parses = []
  parse unless @parses.empty?
end

@parses = [[0]]
@new_parses = []
@completed_parses = []
parse
p @completed_parses

会给你:

[["aba", "aba", "bb", "ab"], ["ab", "aa", "ba", "bb", "ab"]]

我不明白为什么你的回答中有["ab","aab","ab","ba","bab"]