您现在的位置是:主页 > news > 彩票网站怎么做/自媒体135的网站是多少

彩票网站怎么做/自媒体135的网站是多少

admin2025/5/1 15:33:06news

简介彩票网站怎么做,自媒体135的网站是多少,贵州网站建设推荐,如何删除网站后台的文章题目链接: https://leetcode-cn.com/problems/implement-strstr/题目描述实现 strStr() 函数。给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。示例:示例 1:输…

彩票网站怎么做,自媒体135的网站是多少,贵州网站建设推荐,如何删除网站后台的文章题目链接: https://leetcode-cn.com/problems/implement-strstr/题目描述实现 strStr() 函数。给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。示例:示例 1:输…

824006178b5e5921775ea69bc0ff0611.png

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

题目描述

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1

示例:

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2

示例 2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1

说明:

needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

思路:

思路1:调用库函数

思路2:

暴力法,时间复杂度:

,
是主字符串,
是模式字符串.

思路3:

如何更好的理解和掌握 KMP 算法?​www.zhihu.com

讲的特别好!


关注我的知乎专栏,了解更多的解题技巧,大家共同进步!

代码:

思路2:

python

class Solution:def strStr(self, haystack: str, needle: str) -> int:if not needle : return 0n1 = len(haystack)n2 = len(needle)if n1 < n2:return -1def helper(i):haystack_p = ineedle_q = 0while needle_q < n2:if haystack[haystack_p] !=  needle[needle_q]:return Falseelse:haystack_p += 1needle_q += 1return Truefor i in range(n1 - n2 + 1):if helper(i):return ireturn -1

python

class Solution:def strStr(self, haystack: str, needle: str) -> int:for i in range(len(haystack) - len(needle)+1):if haystack[i:i+len(needle)] == needle:return ireturn -1

java

class Solution {public int strStr(String S, String T) {int n1 = S.length();int n2 = T.length();if (n1 < n2) return -1;else if ( n2 == 0) return 0;for (int i = 0; i < n1 - n2 + 1; i++ ){if (S.substring(i, i+n2).equals(T)) return i;}return -1;}
}

思路3

python

class Solution:def strStr(self, t, p):""":type haystack: str:type needle: str:rtype: int"""if not p : return 0_next = [0] * len(p)def getNext(p, _next):_next[0] = -1i = 0j = -1while i < len(p) - 1:if j == -1 or p[i] == p[j]:i += 1j += 1_next[i] = jelse:j = _next[j]getNext(p, _next)i = 0j = 0while i < len(t) and j < len(p):if j == -1 or t[i] == p[j]:i += 1j += 1else:j = _next[j]if j == len(p):return i - jreturn -1

java

class Solution {public int strStr(String S, String T) {if (T == null || T.length() == 0) return 0;int[] next = new int[T.length()];getNext(T, next);int i = 0;int j = 0;while (i < S.length() && j < T.length()) {if (j == -1 || S.charAt(i) == T.charAt(j)) {i++;j++;} else j = next[j];}if (j == T.length()) return i - j;return -1;}private void getNext(String t, int[] next) {next[0] = -1;int i = 0;int j = -1;while (i < t.length() - 1) {if (j == -1 || t.charAt(i) == t.charAt(j)) {i++;j++;next[i] = j;} else {j = next[j];}}}
}

699058fb160fd31df10a8597307635e1.png

同步更新博客:

一起刷LeetCode - 威行天下 - 博客园​www.cnblogs.com