Problem 14: longest common prefix
This commit is contained in:
parent
907dfdf070
commit
d09a4d3eb0
2 changed files with 44 additions and 0 deletions
26
problems/14-longest-common-prefix/main.rb
Normal file
26
problems/14-longest-common-prefix/main.rb
Normal 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
|
18
problems/14-longest-common-prefix/test.rb
Normal file
18
problems/14-longest-common-prefix/test.rb
Normal 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
|
Loading…
Reference in a new issue