算法快速入门
数据结构与算法
//通过:8ms,20.9MB
//https://leetcode-cn.com/problems/implement-strstr/solution/yi-ci-bian-li-haystackhaystackcount-needlecountcha/
func strStr_c(_ haystack: String, _ needle: String) -> Int {
guard !needle.isEmpty else{
return 0
}
let needleCount = needle.count
let haystackCount = haystack.count
guard needleCount <= haystackCount else{
return -1
}
let iRange = 0...(haystackCount - needleCount)
for i in iRange {
let startIndex = haystack.index(haystack.startIndex, offsetBy: i)
let endIndex = haystack.index(startIndex, offsetBy: needleCount)
let haystackRange = haystack[startIndex..<endIndex]
if haystackRange == needle {
return i
}else{
continue
}
}
return -1
}面试注意点
练习
最后更新于