Created
October 18, 2019 08:50
-
-
Save gokhanakkurt/42c15fca1fdacf9a26c18afa62a2fef3 to your computer and use it in GitHub Desktop.
Find longest common prefix string in an array - (swift implementation, slicing method)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func longestCommonPrefix(_ strs: [String]) -> String { | |
// base case | |
if strs.isEmpty { | |
return "" | |
} | |
if var prefixStr = strs.first { | |
for index in 1..<strs.count { | |
let str = strs[index] | |
while str.contains(prefixStr) == false { | |
let index = prefixStr.index(prefixStr.startIndex, offsetBy: prefixStr.count - 1) | |
prefixStr = String(prefixStr[..<index]) | |
if prefixStr.count == 0 { | |
return "" | |
} | |
} | |
} | |
return prefixStr | |
} | |
return "" | |
} | |
longestCommonPrefix(["flower", "florida", "flow"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
will be failed in case like ["c","acc","ccc"]