From d09a4d3eb080132e44b6ad79c16f7529d894bfcb Mon Sep 17 00:00:00 2001 From: Ivan Reshetnikov Date: Sat, 26 Nov 2022 11:27:25 +0500 Subject: [PATCH] Problem 14: longest common prefix --- problems/14-longest-common-prefix/main.rb | 26 +++++++++++++++++++++++ problems/14-longest-common-prefix/test.rb | 18 ++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 problems/14-longest-common-prefix/main.rb create mode 100644 problems/14-longest-common-prefix/test.rb diff --git a/problems/14-longest-common-prefix/main.rb b/problems/14-longest-common-prefix/main.rb new file mode 100644 index 0000000..1aec2df --- /dev/null +++ b/problems/14-longest-common-prefix/main.rb @@ -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 diff --git a/problems/14-longest-common-prefix/test.rb b/problems/14-longest-common-prefix/test.rb new file mode 100644 index 0000000..7332c24 --- /dev/null +++ b/problems/14-longest-common-prefix/test.rb @@ -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