Skip to content

Instantly share code, notes, and snippets.

@Ji-Yuhang
Created June 23, 2016 01:58
Show Gist options
  • Save Ji-Yuhang/b76e15b8a89bb2243d82a8fb3a388598 to your computer and use it in GitHub Desktop.
Save Ji-Yuhang/b76e15b8a89bb2243d82a8fb3a388598 to your computer and use it in GitHub Desktop.
longest common substring, 一组字符串中找出最长的相同部分
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"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment