-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest_common_prefix.rb
51 lines (41 loc) · 972 Bytes
/
longest_common_prefix.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/ruby
# Find the longest common prefix, given a list of words.
def find_common_prefix(hash, acc)
return acc if !hash
if (hash.size == 1)
key = hash.keys[0]
value = hash.values[0]
return find_common_prefix(value, acc + key)
end
return acc
end
def lcp(strs)
hash = {}
for str in (strs.sort_by {|t| t.size })
ref = hash
return "" if str.empty?
for char in (str.chars)
if (ref.has_key?(char))
ref = ref[char]
break if (ref.size == 0)
else
ref = (ref[char] = {})
end
end
end
return find_common_prefix(hash, '')
end
tests = [
["interspecies","interstellar","interstate"],
["throne","throne"],
["throne","dungeon"],
["throne","","throne"],
["cheese"],
[""],
[],
["prefix","suffix"],
["foo","foobar"]
]
for test in tests
puts "lcp(#{test}) = \"#{lcp(test)}\""
end