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 hidden or 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"]) |
If the first word is too long and the other words are short, then your code ends up with character count of the first word iterations of while loop.
Example: ["abcdefgijklmnopqrstuvwxyz", "b"]
My version.
// LC: https://leetcode.com/problems/longest-common-prefix
// TC -> O(min(strs) * n)
// SC -> O(str.first!.count)
func longestCommonPrefix(_ strs: [String]) -> String {
if strs.count == 1 {
return strs.first!
}
guard let temp = strs.first, !temp.isEmpty else {
return ""
}
var endIndex: String.Index? = nil
outerLoop:
for index in temp.indices {
for str in strs {
if str.isEmpty {
return ""
}
// checking index out of range and characters equality
if index >= str.endIndex || str[index] != temp[index] {
break outerLoop
}
}
endIndex = index
}
if let endIndex {
return String(temp[...endIndex])
}
return ""
}
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"]