From a2743f2442c60c95b7aed7591053578d22ccb57a Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 00:38:29 +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 添加 0028.实现strStr Java版本,基于滑动窗口的算法 --- problems/0028.实现strStr.md | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index f1de00f8..c6463e8b 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -565,6 +565,54 @@ public: Java: +```Java +class Solution { + /** + * 基于窗口滑动的算法 + *

+ * 时间复杂度:O(m*n) + * 空间复杂度:O(1) + * 注:n为haystack的长度,m为needle的长度 + */ + public int strStr(String haystack, String needle) { + int m = needle.length(); + // 当 needle 是空字符串时我们应当返回 0 + if (m == 0) { + return 0; + } + int n = haystack.length(); + if (n < m) { + return -1; + } + int i = 0; + int j = 0; + while (i < n - m + 1) { + // 找到首字母相等 + while (i < n && haystack.charAt(i) != needle.charAt(j)) { + i++; + } + if (i == n) {// 没有首字母相等的 + return -1; + } + // 遍历后续字符,判断是否相等 + i++; + j++; + while (i < n && j < m && haystack.charAt(i) == needle.charAt(j)) { + i++; + j++; + } + if (j == m) {// 找到 + return i - j; + } else {// 未找到 + i -= j - 1; + j = 0; + } + } + return -1; + } +} +``` + ```java // 方法一 class Solution {