Created
June 23, 2016 01:58
-
-
Save Ji-Yuhang/b76e15b8a89bb2243d82a8fb3a388598 to your computer and use it in GitHub Desktop.
longest common substring, 一组字符串中找出最长的相同部分
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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