Skip to content

Instantly share code, notes, and snippets.

@itssomething
Created January 23, 2024 19:53
Show Gist options
  • Save itssomething/dc65e0d987fd3ebdf86187bdedf31dd7 to your computer and use it in GitHub Desktop.
Save itssomething/dc65e0d987fd3ebdf86187bdedf31dd7 to your computer and use it in GitHub Desktop.
# @param {String[]} strs
# @return {String}
def longest_common_prefix(strs)
return "" if strs.length == 0
return strs[0] if strs.length == 1
min_length = strs[0].length
strs.each do |str|
min_length = [min_length, str.length].min
end
first_str = strs[0]
strs = strs[1..]
count = -1
exit = false
if min_length == 1
strs.each do |str|
if str[0] == first_str[0]
count = 0
else
count = -1
break
end
end
else
min_length.times do |index|
break if exit
strs.each do |str|
break if exit
if str[index] != first_str[index] && index == 0
exit = true
end
if str[index] != first_str[index]
count = index - 1
exit = true
end
end
if index == min_length - 1 && exit == false
count = index
end
end
end
return "" if count == -1
return first_str[0..count]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment