原题连接:https://leetcode.com/problems/longest-common-prefix/description/
解决:
func longestCommonPrefix(_ strs: [String]) -> String {
if strs.count == 0 {
return ""
} else if strs.count == 1 {
return strs[0]
}
let firtStr = strs[0]
var result = ""
for cha in firtStr {
result = result + String(cha)
var count: Int? = 0
for str in strs {
if str == "" {
result = ""
break
}
if str.hasPrefix(result) && result != "" {
count = count! + 1
}
}
if count == strs.count {
continue
} else {
if result.count > 0 {
result = String(result.prefix(result.count - 1))
}
break;
}
}
return result
}
|
请发表评论