forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestCommonPrefix.swift
34 lines (28 loc) · 1.07 KB
/
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
33
34
/**
* 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 longest prefix
*/
class LongestCommonPrefix {
func longestCommonPrefix(_ strs: [String]) -> String {
guard let firstStr = strs.first else {
return ""
}
var res = ""
for (i, char) in firstStr.enumerated() {
// dropFirst(_ k: Int = 1) returns a Substring struct
for str in strs.dropFirst() {
if i == str.count {
return res
}
// Another easy way: Array(str)[i], time complexity is linear though
let currentStrChar = str[str.index(str.startIndex, offsetBy: i)]
if char != currentStrChar {
return res
}
}
res.append(char)
}
return res
}
}