From 93eada462d65a454b3be91c3d1633c0905b4e495 Mon Sep 17 00:00:00 2001 From: MoguCloud Date: Wed, 11 Nov 2020 13:33:41 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=9028.=E5=AE=9E=E7=8E=B0=20strStr()?= =?UTF-8?q?=E3=80=91=E3=80=90Python=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...71\351\205\215\347\256\227\346\263\225.md" | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git "a/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\345\212\250\346\200\201\350\247\204\345\210\222\344\271\213KMP\345\255\227\347\254\246\345\214\271\351\205\215\347\256\227\346\263\225.md" "b/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\345\212\250\346\200\201\350\247\204\345\210\222\344\271\213KMP\345\255\227\347\254\246\345\214\271\351\205\215\347\256\227\346\263\225.md" index a0cc4ce..5cde805 100644 --- "a/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\345\212\250\346\200\201\350\247\204\345\210\222\344\271\213KMP\345\255\227\347\254\246\345\214\271\351\205\215\347\256\227\346\263\225.md" +++ "b/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\345\212\250\346\200\201\350\247\204\345\210\222\344\271\213KMP\345\255\227\347\254\246\345\214\271\351\205\215\347\256\227\346\263\225.md" @@ -431,4 +431,40 @@ KMP 算法也就是动态规划那点事,我们的公众号文章目录有一

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== +[MoguCloud](https://github.com/MoguCloud) 提供 实现 strStr() 的 Python 完整代码: +```py +class Solution: + def strStr(self, haystack: str, needle: str) -> int: + # 边界条件判断 + if not needle: + return 0 + pat = needle + txt = haystack + + M = len(pat) + # dp[状态][字符] = 下个状态 + dp = [[0 for _ in range(256)] for _ in pat] + # base case + dp[0][ord(pat[0])] = 1 + # 影子状态 X 初始化为 0 + X = 0 + for j in range(1, M): + for c in range(256): + dp[j][c] = dp[X][c] + dp[j][ord(pat[j])] = j + 1 + # 更新影子状态 + X = dp[X][ord(pat[j])] + + N = len(txt) + # pat 初始状态为 0 + j = 0 + for i in range(N): + # 计算 pat 的下一个状态 + j = dp[j][ord(txt[i])] + # 到达终止态,返回结果 + if j == M: + return i - M + 1 + # 没到达终止态,匹配失败 + return -1 +``` -- GitLab