forked from NilaakashSingh/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestCommonPrefix.swift
37 lines (28 loc) · 1.13 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
35
36
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 longest prefix
*/
class LongestCommonPrefix {
func longestCommonPrefix(_ strs: [String]) -> String {
var longestPrefix = [Character](), index = 0
guard let firstStr = strs.first else {
return String(longestPrefix)
}
let firstStrChars = Array(firstStr)
let strsChars = strs.map { Array($0) }
while index < firstStr.count {
longestPrefix.append(firstStrChars[index])
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(longestPrefix)
}
}