Last active
September 16, 2019 00:01
-
-
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.
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 { | |
| 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