[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: common prefix?
- From: Scott Fial <scott@...>
- Date: Fri, 21 Jun 2013 01:07:19 -0700
Perhaps I'm a bit late to the party, but here's my submission for
computing the longest common prefix found in a list of strings:
function longest_common_prefix(t)
local t1, n, byte = t[1] or "", #t, string.byte
for i = 1, #t1 do
local b = byte(t1, i)
for j = 2, n do
if byte(t[j], i) ~= b then return t1:sub(1, i - 1) end
end
end
return t1
end
NOTE: It returns t[1] when #t == 1. If you'd prefer that it return an
empty string in that case, change line 2 to read:
local t1, n, byte = #t > 1 and t[1] or "", #t, string.byte