my-solutions/problems/14-longest-common-prefix/main.rb

22 lines
387 B
Ruby
Raw Normal View History

2022-11-26 11:27:25 +05:00
# @param {String[]} strs
# @return {String}
def longest_common_prefix(strs)
# Find min length
min_length = strs.map{|s| s.length}.min()
2022-11-26 11:27:25 +05:00
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