https://leetcode-cn.com/problems/longest-common-prefix/
func longestCommonPrefix(_ strs: [String]) -> String {
if strs.count <= 0 {return ""}
var preStr = strs[0]
for (index, str) in strs.enumerated() {
if index == 0 {continue}
while !str.hasPrefix(preStr) {
let startIndex = preStr.index(preStr.startIndex, offsetBy: 0)
let endIndex = preStr.index(preStr.startIndex, offsetBy: (preStr.count - 1))
//每次删除末尾一个字符
let tmpStr = preStr[startIndex..<endIndex]
preStr = String(tmpStr)
if preStr.count == 0 {return ""}
}
}
return preStr
}
网友评论