strstr函数_[LeetCode] 28. 实现strStr()
生活随笔
收集整理的這篇文章主要介紹了
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 -1python
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 -1java
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 -1java
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()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 工艺路线和工序有差别吗_智能制造、数字化
- 下一篇: url模糊匹配优化_详情页怎么做SEO优