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] add Solution to Longest Common Prefix
- Loading branch information
Yi Gu
committed
Jun 5, 2016
1 parent
d00f3c2
commit aabbbd5
Showing
1 changed file
with
32 additions
and
0 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 |
---|---|---|
@@ -0,0 +1,32 @@ | ||
/** | ||
* 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 | ||
*/ | ||
|
||
class LongestCommonPrefix { | ||
func longestCommonPrefix(strs: [String]) -> String { | ||
guard strs.count > 0 else { | ||
return "" | ||
} | ||
|
||
var res = [Character](strs[0].characters) | ||
|
||
for str in strs { | ||
var strContent = [Character](str.characters) | ||
|
||
if res.count > strContent.count { | ||
res = Array(res[0 ..< strContent.count]) | ||
} | ||
|
||
for i in 0 ..< res.count { | ||
if res[i] != strContent[i] { | ||
res = Array(res[0 ..< i]) | ||
break | ||
} | ||
} | ||
} | ||
|
||
return String(res) | ||
} | ||
} |