Skip to content

Commit

Permalink
Handle trivial input better in 14.longest-common-prefix.jl (#172)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
GHTaarn authored Feb 20, 2024
1 parent 7452e24 commit e5daa11
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/problems/14.longest-common-prefix.jl
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ using LeetCode
function longest_common_prefix(strs::Vector{String})::String
s1, s2 = minimum(strs), maximum(strs)
pos = findfirst(i -> s1[i] != s2[i], 1:length(s1))
return isnothing(pos) ? "" : s1[1:(pos - 1)]
return isnothing(pos) ? s1 : s1[1:(pos - 1)]
end

## @lc code=end
3 changes: 3 additions & 0 deletions test/problems/14.longest-common-prefix.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@
@test longest_common_prefix(["flower", "flow", "flight"]) == "fl"
@test longest_common_prefix(["dog", "racecar", "car"]) == ""
@test longest_common_prefix(["reflower", "flow", "flight"]) == ""
@test longest_common_prefix(["abc"]) == "abc"
@test longest_common_prefix(fill("abc", 5)) == "abc"
@test longest_common_prefix(fill("", 4)) == ""
end

0 comments on commit e5daa11

Please sign in to comment.