Skip to content

Instantly share code, notes, and snippets.

@lrechert
Last active April 18, 2016 18:42
Show Gist options
  • Select an option

  • Save lrechert/ef22fade081d2e220baa to your computer and use it in GitHub Desktop.

Select an option

Save lrechert/ef22fade081d2e220baa to your computer and use it in GitHub Desktop.
Ruby Weekly Challenge - String Prefixes
# Two strings have a common prefix that consists of the longest prefix of the strings that is the same.
# For instance, the strings “I love cats” and “I love dogs” have the common prefix “I love ”
# (including a trailing space at the end of love, which doesn’t appear properly in some browsers).
# Your task is to write a program that finds the common prefix of a list of strings (possibly more than two strings).
# Algo:
# 1. find length of shortest sting in arr since this is the max longest-prefix length
# 2. iterate over each string in arr, comparing against the substring
# 3. if we reach the end of arr, return the calculated prefix as the longest.
def shortest_string(arr)
return '' if arr.nil? || arr.empty?
arr.compact.min { |a, b| a.size <=> b.size }
end
def longest_common_prefix(arr)
return '' if arr.nil? || arr.empty? || arr.compact.empty?
arr.compact!
(0..shortest_string(arr).size-1).reverse_each do |i|
arr.each_with_index do |s, arr_idx|
break unless s && s[0..i] == arr[0][0..i]
return arr[0][0..i] if s[0..i] == arr[0][0..i] && arr_idx == arr.size-1
end
end
''
end
require_relative '../longest_common_prefix'
describe "#longest_common_prefix" do
context "when arr is nil" do
it "returns an empty string" do
expect(longest_common_prefix nil).to eq('')
end
end
context "when arr has one element" do
it "returns the string" do
expect(longest_common_prefix(["i love"])).to eq('i love')
end
context "when arr has a single nil element" do
it "returns an empty string" do
expect(longest_common_prefix([nil])).to eq('')
end
end
end
context "when arr has more than one element" do
context "when there is a common prefix" do
it "returns the common prefix" do
expect(longest_common_prefix(['i lo', 'i love cats', 'i l ', 'i love dogs', 'i love my daughter'])).to eq('i l')
end
end
context "when there is not a common prefix" do
it "returns the empty string" do
expect(longest_common_prefix(['love', 'hate'])).to eq('')
end
end
context "when there is a nil element" do
it "ignores nil" do
expect(longest_common_prefix(['i lo', 'i love cats', 'i l', 'i love dogs', 'i love my daughter', nil])).to eq('i l')
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment