Skip to content

Commit e5daa11

Browse files
authored
Handle trivial input better in 14.longest-common-prefix.jl (#172)
* Improve 14.longest-common-prefix.jl This change makes the algorithm able to handle trivial cases where there is only one input string or where all input strings are equal * More tests for 14.longest-common-prefix.jl
1 parent 7452e24 commit e5daa11

File tree

2 files changed

+4
-1
lines changed

2 files changed

+4
-1
lines changed

src/problems/14.longest-common-prefix.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ using LeetCode
4848
function longest_common_prefix(strs::Vector{String})::String
4949
s1, s2 = minimum(strs), maximum(strs)
5050
pos = findfirst(i -> s1[i] != s2[i], 1:length(s1))
51-
return isnothing(pos) ? "" : s1[1:(pos - 1)]
51+
return isnothing(pos) ? s1 : s1[1:(pos - 1)]
5252
end
5353

5454
## @lc code=end

test/problems/14.longest-common-prefix.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,7 @@
22
@test longest_common_prefix(["flower", "flow", "flight"]) == "fl"
33
@test longest_common_prefix(["dog", "racecar", "car"]) == ""
44
@test longest_common_prefix(["reflower", "flow", "flight"]) == ""
5+
@test longest_common_prefix(["abc"]) == "abc"
6+
@test longest_common_prefix(fill("abc", 5)) == "abc"
7+
@test longest_common_prefix(fill("", 4)) == ""
58
end

0 commit comments

Comments
 (0)