14. 最长公共前缀
Show me the code
swift
class Solution {
func longestCommonPrefix(_ strs: [String]) -> String {
var ret = ""
var stop = false
let firstString = strs.first!
guard !firstString.isEmpty else {
// 首个字符串是""
return ""
}
var prefix = ""
for maxLength in 1...firstString.count {
prefix = String(firstString.prefix(maxLength))
for str in strs {
if !str.hasPrefix(prefix) {
ret = String(firstString.prefix(maxLength - 1))
stop = true
break
}
}
if stop {
break
}
}
// 首个str整个都是前缀
if !stop {
ret = firstString
}
return ret
}
}