Skip to content

Commit aa5c773

Browse files
committed
new file: Text/longest_common_prefix.rb
1 parent ab5cfe1 commit aa5c773

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,6 @@ A small collection of day-to-day Ruby scripts used in solving problems or in imp
1717
* [Roman numerals decode](./Math/roman_numerals_decode.rb)
1818
* [Roman numerals encode](./Math/roman_numerals_encode.rb)
1919
* Text
20+
* [Longest common prefix](./Text/longest_common_prefix.rb)
2021
* [Smart word wrap](./Text/smart_word_wrap.rb)
2122
* [Smart word wrap lazy](./Text/smart_word_wrap_lazy.rb)

Text/longest_common_prefix.rb

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

0 commit comments

Comments
 (0)