From ac3f9b8d705a07001590097e0362a6e31dd19b79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9CDraymondHIT=E2=80=9D?= <“3343033352@qq.com”> Date: Sat, 11 Feb 2023 16:58:40 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200028=E6=89=BE=E5=87=BA?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E4=B8=AD=E7=AC=AC=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E5=8C=B9=E9=85=8D=E9=A1=B9=E7=9A=84=E4=B8=8B=E6=A0=87=20?= =?UTF-8?q?=E5=89=8D=E7=BC=80=E8=A1=A8=EF=BC=88=E4=B8=8D=E5=87=8F=E4=B8=80?= =?UTF-8?q?=EF=BC=89=20Python=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0028.实现strStr.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index 4e01926f..2757130c 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -769,6 +769,36 @@ class Solution: return next ``` +```python +// 前缀表(不减一)Python实现 +class Solution: + def strStr(self, haystack: str, needle: str) -> int: + if len(needle) == 0: + return 0 + next = self.getNext(needle) + j = 0 + for i in range(len(haystack)): + while j >= 1 and haystack[i] != needle[j]: + j = next[j-1] + if haystack[i] == needle[j]: + j += 1 + if j == len(needle): + return i - len(needle) + 1 + return -1 + + def getNext(self, needle): + next = [0] * len(needle) + j = 0 + next[0] = j + for i in range(1, len(needle)): + while j >= 1 and needle[i] != needle[j]: + j = next[j-1] + if needle[i] == needle[j]: + j += 1 + next[i] = j + return next +``` + Go: ```go @@ -1352,3 +1382,4 @@ impl Solution { +