在字符串数组中查找公共字符串(ruby) [英] Finding common string in array of strings (ruby)

查看:57
本文介绍了在字符串数组中查找公共字符串(ruby)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含 3 个字符串的数组:

Given I have an array of 3 strings:

["Extra tv in bedroom",
 "Extra tv in living room",
 "Extra tv outside the shop"]

如何找到所有字符串共有的最长字符串?

How do I find the longest string all strings have in common?

推荐答案

这里有一个红宝石般的方法.但是,如果您有一堆字符串或它们很长,则应该使用更高级的算法:

Here's a rubyish way of doing it. You should use a more advanced algorithm if you have a bunch of strings or they are very long, though:

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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆