ruby 最长的共同子串,一组字符串中找出最长的相同部分

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 最长的共同子串,一组字符串中找出最长的相同部分相关的知识,希望对你有一定的参考价值。

def longest_common_substr(strings)
  shortest = strings.min_by &:length
  maxlen = shortest.length
  maxlen.downto(0) do |len|
    0.upto(maxlen - len) do |start|
      substr = shortest[start,len]
      return substr if strings.all?{|str| str.include? substr }
    end
  end
end

puts longest_common_substr(["Extra tv in bedroom",
                            "Extra tv in living room",
                            "Extra tv outside the shop"])

以上是关于ruby 最长的共同子串,一组字符串中找出最长的相同部分的主要内容,如果未能解决你的问题,请参考以下文章