Skip to content

Instantly share code, notes, and snippets.

@jakehawken
Last active September 16, 2019 00:01
Show Gist options
  • Select an option

  • Save jakehawken/5e4374000f40aaad33bae18231af8736 to your computer and use it in GitHub Desktop.

Select an option

Save jakehawken/5e4374000f40aaad33bae18231af8736 to your computer and use it in GitHub Desktop.
Leetcode #14: Finds the longest common prefix between the strings in an array.
func longestCommonPrefix(_ strs: [String]) -> String {
var shortest = Int.max
let charArrays = strs.map { (string) -> [Character] in
let array = Array(string)
shortest = min(shortest, array.count)
return array
}
var outputChars = [Character]()
for i in 0..<shortest {
let ithChars = charArrays.map { $0[i] }
let charSet = Set(ithChars)
if charSet.count > 1 {
break
}
else if let only = charSet.first {
outputChars.append(only)
}
else {
break
}
}
return String(outputChars)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment