StarryNights

每一个你所后悔的现在,都有一个不够努力的曾经

站内检索

循着字句,邂逅星光

搜索文章标题与正文,直达命中的章节

开始一次轻盈的站内探索

从这些主题开始探索

输入关键词

可同时输入多个词语缩小范围

发现内容

在摘要中查看高亮的关键词

快速直达

点击文章或章节标题继续阅读

# 引言

题目链接:https://leetcode.com/problems/implement-strstr/

# 题目大意

实现strStr()

返回haystack中第一次出现模式串的索引, 如果模式串不是haystack的一部分, 则返回-1。

Hint: 当模式串为空的时候, 返回0(没看到这个居然被坑了T_T)

  • Example
Input: haystack = "hello", needle = "ll"
Output: 2

Input: haystack = "aaaaa", needle = "bba"
Output: -1

# 题解

# 一句话题解

KMP算法, 关于KMP算法推荐一篇感觉讲的很有灵魂的博客! Click Here!

# 复杂度

时间复杂度 O(n+m)

空间复杂度 O(m), m代表模式串(需要匹配的字符串)的长度

# AC代码

c++版本

class Solution
{
  public:
    int strStr(string haystack, string needle)
    {
        int len = needle.length();
        if (len <= 0)
        {
            return 0;
        }
        int *next = getNext(needle);
        int ret = -1;
        for (int i = 0, j = 0; i < haystack.length(); ++i)
        {
            while (j > 0 && haystack[i] != needle[j])
            {
                j = next[j];
            }
            if (haystack[i] == needle[j])
            {
                ++j;
            }
            if (j == len)
            {
                ret = i - j + 1;
                break;
            }
        }
        delete[] next;
        return ret;
    }

  private:
    int *getNext(const string &needle)
    {
        int *next = new int[needle.length() + 1];
        next[0] = next[1] = 0;
        for (int i = 1, j = 0; i < needle.length(); ++i)
        {
            while (j > 0 && needle[j] != needle[i])
            {
                j = next[j];
            }
            next[i + 1] = needle[j] == needle[i] ? ++j : j;
        }
        return next;
    }
};

go版本

func getNext(needle string) []int {
	lens := len(needle)
	next := make([]int, lens+1)
	for i, j := 1, 0; i < lens; i++ {
		for j > 0 && needle[j] != needle[i] {
			j = next[j]
		}
		if needle[i] == needle[j] {
			j++
		}
		next[i+1] = j
	}
	return next
}

func strStr(haystack string, needle string) int {
	len1 := len(needle)
	if len1 <= 0 {
		return 0
	}
	ret, next, len2 := -1, getNext(needle), len(haystack)
	for i, j := 0, 0; i < len2; i++ {
		for j > 0 && haystack[i] != needle[j] {
			j = next[j]
		}
		if haystack[i] == needle[j] {
			j++
		}
		if j == len1 {
			ret = i - j + 1
			break
		}
	}
	return ret
}
更新于 阅读次数 — 次
STARRY NIGHTSPERSONAL NOTES

赞赏

文章至此,故事还在继续。

Seiun

长按或右键保存收款码

文章关联

1 篇关联

顺着引用的连线,读见篇章交错的脉络

展开关系图

拖动平移 · Ctrl / ⌘ + 滚轮缩放 · 点击节点阅读使用 + / − 按钮缩放 · 放大视图后可拖动 · 点击节点阅读单指拖动平移 · 使用 + / − 按钮缩放 · 点击节点阅读

当前文章引用本文
引用列表

引用本文1

  • LeetCode Programming
    AI 摘要

    本文是作者为缓解拖延、练习 Go 语言而开启的 LeetCode 刷题记录,兼作个人题解。文中先介绍 C++ 输入输出加速技巧,通过 ios::sync_with_stdio(false) 解除 C/C++ 流同步、cin.tie(nullptr) 解除 cin 与 cout 绑定来提升效率;随后汇总多道 LeetCode 题解,列出题号、题目、难度及链接,涵盖第1至32题等。

本文引用0

暂无

文章关联