From a981cee54cad59114335f32bcb88b4a2e39d0342 Mon Sep 17 00:00:00 2001 From: ShrinkLynn Date: Sun, 12 Dec 2021 19:54:33 +0800 Subject: [PATCH] [ShrinkLynn] 0028 add swift version --- problems/0028.实现strStr.md | 51 +++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index 1c654dd4..d6c5ee27 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -894,7 +894,58 @@ var strStr = function (haystack, needle) { }; ``` +Swift 版本 +> 前缀表统一减一 + +```swift +func strStr(_ haystack: String, _ needle: String) -> Int { + + let s = Array(haystack), p = Array(needle) + guard p.count != 0 else { return 0 } + + // 2 pointer + var j = -1 + var next = [Int](repeating: -1, count: needle.count) + // KMP + getNext(&next, needle: p) + for i in 0 ..< s.count { + while j >= 0 && s[i] != p[j + 1] { + //不匹配之后寻找之前匹配的位置 + j = next[j] + } + if s[i] == p[j + 1] { + //匹配,双指针同时后移 + j += 1 + } + if j == (p.count - 1) { + //出现匹配字符串 + return i - p.count + 1 + } + } + return -1 +} + +//前缀表统一减一 +func getNext(_ next: inout [Int], needle: [Character]) { + + var j: Int = -1 + next[0] = j + + // i 从 1 开始 + for i in 1 ..< needle.count { + while j >= 0 && needle[i] != needle[j + 1] { + j = next[j] + } + if needle[i] == needle[j + 1] { + j += 1; + } + next[i] = j + } + print(next) +} + +``` -----------------------