Skip to content

Commit 71b1781

Browse files
committed
Longest Common Prefix
1 parent 112c94b commit 71b1781

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
Not only Leetcode solutions in Swift.
44

55
* [1. Two Sum](https://leetcode.com/problems/two-sum/)
6+
* [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)
67
* [15. 3Sum](https://leetcode.com/problems/3sum/)
78
* [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/)
89
* [18. 4Sum](https://leetcode.com/problems/4sum/)

SwiftyLeetCode.playground/Contents.swift

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,42 @@ let twoSumTarget = 9
3737

3838
Solution.twoSum(nums: twoSumNums, twoSumTarget)
3939

40+
/**
41+
* 14. Longest Common Prefix
42+
* https://leetcode.com/problems/longest-common-prefix/
43+
44+
*/
45+
46+
extension Solution {
47+
class func longestCommonPrefix(strs: [String]?) -> String? {
48+
guard let strs = strs, strs.count > 0 else {
49+
return nil
50+
}
51+
52+
var prefix = strs[0]
53+
for i in 1..<strs.count {
54+
var j = 0
55+
let str = strs[i]
56+
let strCount = str.characters.count
57+
let prefixCount = prefix.characters.count
58+
while (j < strCount && j < prefixCount && str[str.index(str.startIndex, offsetBy: j)] == prefix[prefix.index(str.startIndex, offsetBy: j)]) {
59+
j += 1
60+
}
61+
if j == 0 {
62+
return ""
63+
}
64+
65+
prefix = prefix.substring(to: prefix.index(str.startIndex, offsetBy: j))
66+
}
67+
return prefix
68+
}
69+
}
70+
71+
// usage
72+
73+
let longestCommonPrefixStrs = ["geeksforgeeks", "geeks", "geek", "geezer"]
74+
Solution.longestCommonPrefix(strs: longestCommonPrefixStrs)
75+
4076
/**
4177
* 15. 3Sum
4278
* https://leetcode.com/problems/3sum/

0 commit comments

Comments
 (0)