Problem 14: longest common prefix

This commit is contained in:
Ivan R. 2022-11-26 11:27:25 +05:00
parent 907dfdf070
commit d09a4d3eb0
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
2 changed files with 44 additions and 0 deletions

View file

@ -0,0 +1,26 @@
# @param {String[]} strs
# @return {String}
def longest_common_prefix(strs)
# Find min length
min_length = strs[0].length
strs.each do |st|
if st.length < min_length
min_length = st.length
end
end
res = ""
for i in 0..min_length - 1 do
strs.each do |st|
# If characters doesn't match
if st[i] != strs[0][i]
return res
end
end
# All characters match
res += strs[0][i]
end
return res
end

View file

@ -0,0 +1,18 @@
require_relative "main"
require "test/unit"
class TestLCP < Test::Unit::TestCase
def test_simple
assert_equal("fl", longest_common_prefix(["flower","flow","flight"]) )
end
def test_empty_prefix
assert_equal("", longest_common_prefix(["dog","racecar","car"]) )
end
def test_empty_string
assert_equal("", longest_common_prefix([""]) )
end
end