Skip to content

Instantly share code, notes, and snippets.

@gokhanakkurt
Created October 18, 2019 08:50
Show Gist options
  • Save gokhanakkurt/42c15fca1fdacf9a26c18afa62a2fef3 to your computer and use it in GitHub Desktop.
Save gokhanakkurt/42c15fca1fdacf9a26c18afa62a2fef3 to your computer and use it in GitHub Desktop.
Find longest common prefix string in an array - (swift implementation, slicing method)
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"])
@PeterPaktorDev
Copy link

will be failed in case like ["c","acc","ccc"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment