日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

strstr函数_[LeetCode] 28. 实现strStr()

發布時間:2024/1/23 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 strstr函数_[LeetCode] 28. 实现strStr() 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目鏈接: 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];}}} }


同步更新博客:

一起刷LeetCode - 威行天下 - 博客園?www.cnblogs.com

總結

以上是生活随笔為你收集整理的strstr函数_[LeetCode] 28. 实现strStr()的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。