1
1
/**
2
2
* Question Link: https://leetcode.com/problems/longest-common-prefix/
3
3
* Primary idea: Use the first string as the result at first, trim it while iterating the array
4
- * Time Complexity: O(nm), Space Complexity: O(m), m stands for the length of first string
4
+ * Time Complexity: O(nm), Space Complexity: O(m), m stands for the length of longest prefix
5
5
*/
6
6
7
7
class LongestCommonPrefix {
8
- func longestCommonPrefix( strs: [ String ] ) -> String {
9
- guard strs. count > 0 else {
10
- return " "
8
+ func longestCommonPrefix( _ strs: [ String ] ) -> String {
9
+ var longestPrefix = [ Character] ( ) , index = 0
10
+
11
+ guard let firstStr = strs. first else {
12
+ return String ( longestPrefix)
11
13
}
12
-
13
- var res = [ Character] ( strs [ 0 ] . characters)
14
14
15
- for str in strs {
16
- var strContent = [ Character] ( str. characters)
15
+ let firstStrChars = Array ( firstStr)
16
+ let strsChars = strs. map { Array ( $0) }
17
+
18
+ while index < firstStr. count {
17
19
18
- if res. count > strContent. count {
19
- res = Array ( res [ 0 ..< strContent. count] )
20
- }
20
+ longestPrefix. append ( firstStrChars [ index] )
21
21
22
- for i in 0 ..< res. count {
23
- if res [ i] != strContent [ i] {
24
- res = Array ( res [ 0 ..< i] )
25
- break
22
+ for str in strsChars {
23
+ if index >= str. count {
24
+ return String ( longestPrefix. dropLast ( ) )
25
+ }
26
+
27
+ if str [ index] != longestPrefix [ index] {
28
+ return String ( longestPrefix. dropLast ( ) )
26
29
}
27
30
}
31
+
32
+ index += 1
28
33
}
29
34
30
- return String ( res )
35
+ return String ( longestPrefix )
31
36
}
32
37
}
0 commit comments