美文网首页
28. 实现 strStr()

28. 实现 strStr()

作者: 寂灭天骄小童鞋 | 来源:发表于2020-03-16 12:57 被阅读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
}

相关文章

网友评论

      本文标题:28. 实现 strStr()

      本文链接:https://www.haomeiwen.com/subject/qqbhjhtx.html