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

19 lines
319 B
Ruby
Raw Normal View History

2022-11-26 11:27:25 +05:00
# @param {String[]} strs
# @return {String}
def longest_common_prefix(strs)
2022-11-26 16:14:11 +05:00
min_length = strs.map(&:length).min
res = ''
(0...min_length).each do |i|
# Compare characters
2022-11-26 11:27:25 +05:00
strs.each do |st|
2022-11-26 16:14:11 +05:00
return res if st[i] != strs[0][i]
2022-11-26 11:27:25 +05:00
end
2022-11-26 16:14:11 +05:00
2022-11-26 11:27:25 +05:00
# All characters match
res += strs[0][i]
end
2022-11-26 16:14:11 +05:00
res
2022-11-26 11:27:25 +05:00
end