1

给定两个字符串,如下所示,我想将它们合并以生成以下内容。结果没有什么意义,但是,两个字符串都有一个共同的“句子”,这就是两个字符串之间的连接符:

"This is a sentence is a great thing"

s1 = "This is a sentence" 

s2 = "a sentence is a great thing"

ruby 有这个功能吗?

4

4 回答 4

2

这是一个有效的解决方案。

def str_with_overlap(s1, s2)
  result = nil
  (0...(s2.length)).each do |idx|
    break result = s1 + s2[(idx + 1)..-1] if s1.end_with?(s2[0..idx])
  end
  result
end

str_with_overlap("This is a sentence", "a sentence is a great thing")
# => This is a sentence is a great thing
于 2012-06-10T09:09:16.860 回答
1

Ruby 中没有内置方法,但你可以试试这个

class String
  def merge str
    result = self + str
    for i in 1..[length,str.length].min
      result = self[0,length-i] + str if self[-i,i] == str[0,i]
    end
    result
  end
end

"This is a sentence".merge "a sentence is a great thing"
于 2012-06-10T09:19:30.760 回答
1

据我所知,Ruby 中没有内置函数。

您可能必须为此编写一个自己的函数。直接的一个在输入长度上以二次时间运行。但是,使用此算法可以在输入大小的线性时间内完成。

于 2012-06-10T08:35:13.987 回答
0

功能方法(在单词级别工作):

ws1, ws2 = [s1, s2].map(&:split)
idx = 0.upto(ws1.size-1).detect { |i| ws1[i..-1] == ws2[0, ws1.size-i] } || 0
(ws1[0, ws1.size-idx] + ws2).join(" ")
=> "This is a sentence is a great thing"
于 2012-06-10T12:39:50.460 回答