-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05_longest_common_prefix.jl
84 lines (56 loc) · 1.62 KB
/
05_longest_common_prefix.jl
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#=
Problem 5: Longest common prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Credits: LeetCode. All rights reserved.
Solution author: Bruno Jacob, UCSB
=#
using BenchmarkTools
function longest_common_prefix(x::Array{String,1})
"""
longest_common_prefix(x::Array{String,1}) -> String
Finds the longest common prefix string amongst an array of strings.
If no prefix is found, returns an empty string "".
Example:
longest_common_prefix(["flower","flow","flight"])
Input: ["flower","flow","flight"]
Output: "fl"
"""
# Default empty string
prefix = string()
if (length(x) == 1)
return x
end
# Sort string by length
sort!(x, by=length)
# Store first element of sorted list
word = x[1]
deleteat!(x,1)
# Length of the shortest word
len_word = length(word)
# Loop over characters of the shortest word and assemble prefix string
for i in 1:len_word
c = word[i]
# Checks if first entry is present in all words of x
if all( [a[i] == c for a in x] )
prefix *= c
else
break
end
end
return prefix
end
# Example parameter:
#a = longest_common_prefix(["flower","flow","flight"])
#println(a)
# To benchmark:
bm = @benchmark longest_common_prefix(x) setup=(x=["flower","flow","flight"])
display(bm)