-
Notifications
You must be signed in to change notification settings - Fork 18
/
LongestCommonPrefix.swift
32 lines (27 loc) · 970 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
//Sayed Mahmudul Alam
//Find the longest common prefix
class LongestCommonPrefix {
func find(_ strs: [String]) -> String {
var minLength = Int.max;
var shortestString:String?
var set = Set<Character>()
for i in strs {
if(i.characters.count < minLength) {
minLength = i.characters.count
shortestString = i
}
}
if var shortestString = shortestString {
var endIndex = shortestString.endIndex
for str in strs {
while !shortestString.isEmpty && !str.hasPrefix(shortestString) {
endIndex = shortestString.index(before: endIndex)
shortestString = shortestString.substring(to: endIndex)
}
}
return shortestString
} else {
return ""
}
}
}