forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[String] Update solution to Longest Common Prefix
- Loading branch information
Showing
1 changed file
with
21 additions
and
16 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,37 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/longest-common-prefix/ | ||
* Primary idea: Use the first string as the result at first, trim it while iterating the array | ||
* Time Complexity: O(nm), Space Complexity: O(m), m stands for the length of first string | ||
* Time Complexity: O(nm), Space Complexity: O(m), m stands for the length of longest prefix | ||
*/ | ||
|
||
class LongestCommonPrefix { | ||
func longestCommonPrefix(strs: [String]) -> String { | ||
guard strs.count > 0 else { | ||
return "" | ||
func longestCommonPrefix(_ strs: [String]) -> String { | ||
var longestPrefix = [Character](), index = 0 | ||
|
||
guard let firstStr = strs.first else { | ||
return String(longestPrefix) | ||
} | ||
|
||
var res = [Character](strs[0].characters) | ||
|
||
for str in strs { | ||
var strContent = [Character](str.characters) | ||
let firstStrChars = Array(firstStr) | ||
let strsChars = strs.map { Array($0) } | ||
|
||
while index < firstStr.count { | ||
|
||
if res.count > strContent.count { | ||
res = Array(res[0..<strContent.count]) | ||
} | ||
longestPrefix.append(firstStrChars[index]) | ||
|
||
for i in 0..<res.count { | ||
if res[i] != strContent[i] { | ||
res = Array(res[0..<i]) | ||
break | ||
for str in strsChars { | ||
if index >= str.count { | ||
return String(longestPrefix.dropLast()) | ||
} | ||
|
||
if str[index] != longestPrefix[index] { | ||
return String(longestPrefix.dropLast()) | ||
} | ||
} | ||
|
||
index += 1 | ||
} | ||
|
||
return String(res) | ||
return String(longestPrefix) | ||
} | ||
} |