forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
LongestCommonPrefix.swift
32 lines (26 loc) · 951 Bytes
/
LongestCommonPrefix.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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)
}
}