28. 实现 strStr()

2020-03-16  本文已影响0人  寂灭天骄小童鞋

https://leetcode-cn.com/problems/implement-strstr/

//粗暴
func strStr(_ haystack: String, _ needle: String) -> Int {
    if needle.count <= 0 {return 0}
    if haystack.count <= 0 {return -1}
    for idx in stride(from: 0, to: haystack.count - needle.count + 1, by: 1) {
        let sub = haystack[haystack.index(haystack.startIndex, offsetBy: idx)...haystack.index(haystack.startIndex, offsetBy: idx + needle.count - 1)]
        if sub == needle {
            return idx
        }
    }
    return -1
}
上一篇下一篇

猜你喜欢

热点阅读