From ccfa2c495fc5c7762517dc990a2fe58328a3292a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AD=9F=E4=BB=A4=E4=BB=A4?= Date: Fri, 8 Apr 2022 18:02:30 +0800 Subject: [PATCH] =?UTF-8?q?Update=200028.=E5=AE=9E=E7=8E=B0strStr.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 swift 前缀表两种实现方法 --- problems/0028.实现strStr.md | 107 ++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index 634d8535..d67e5f70 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -1059,5 +1059,112 @@ func getNext(_ next: inout [Int], needle: [Character]) { ``` +> 前缀表右移 + +```swift +func strStr(_ haystack: String, _ needle: String) -> Int { + + let s = Array(haystack), p = Array(needle) + guard p.count != 0 else { return 0 } + + var j = 0 + var next = [Int].init(repeating: 0, count: p.count) + getNext(&next, p) + + for i in 0 ..< s.count { + + while j > 0 && s[i] != p[j] { + j = next[j] + } + + if s[i] == p[j] { + j += 1 + } + + if j == p.count { + return i - p.count + 1 + } + } + + return -1 + } + + // 前缀表后移一位,首位用 -1 填充 + func getNext(_ next: inout [Int], _ needle: [Character]) { + + guard needle.count > 1 else { return } + + var j = 0 + next[0] = j + + for i in 1 ..< needle.count-1 { + + while j > 0 && needle[i] != needle[j] { + j = next[j-1] + } + + if needle[i] == needle[j] { + j += 1 + } + + next[i] = j + } + next.removeLast() + next.insert(-1, at: 0) + } +``` + +> 前缀表统一不减一 +```swift + +func strStr(_ haystack: String, _ needle: String) -> Int { + + let s = Array(haystack), p = Array(needle) + guard p.count != 0 else { return 0 } + + var j = 0 + var next = [Int](repeating: 0, count: needle.count) + // KMP + getNext(&next, needle: p) + + for i in 0 ..< s.count { + while j > 0 && s[i] != p[j] { + j = next[j-1] + } + + if s[i] == p[j] { + j += 1 + } + + if j == p.count { + return i - p.count + 1 + } + } + return -1 + } + + //前缀表 + func getNext(_ next: inout [Int], needle: [Character]) { + + var j = 0 + next[0] = j + + for i in 1 ..< needle.count { + + while j>0 && needle[i] != needle[j] { + j = next[j-1] + } + + if needle[i] == needle[j] { + j += 1 + } + + next[i] = j + + } + } + +``` + -----------------------