廣州公司網站制作招聘信息網站關鍵詞優(yōu)化的價格
28 實現(xiàn) strStr()
實現(xiàn) strStr() 函數(shù)。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現(xiàn)的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例 1: 輸入: haystack = “hello”, needle = “l(fā)l” 輸出: 2
示例 2: 輸入: haystack = “aaaaa”, needle = “bba” 輸出: -1
說明: **當 needle 是空字符串時,我們應當返回什么值呢?這是一個在面試中很好的問題。 對于本題而言,當 needle 是空字符串時我們應當返回 0 **。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。
思路
首先是模式串匹配問題,需要先在hatstack(文本串)中找到needle子串(模式串),然后再去考慮求這個索引。第一個問題就涉及到KMP算法。KMP的經典思想就是:當出現(xiàn)字符串不匹配時,可以記錄一部分之前已經匹配的文本內容,利用這些信息避免從頭再去做匹配。
以下代碼隨想錄文字詳細說明了KMP算法:
https://www.programmercarl.com/0028.%E5%AE%9E%E7%8E%B0strStr.html#%E6%80%9D%E8%B7%AF
解法一-前綴表(減一)
class Solution(object):# 第一步 首先要求next數(shù)組def getNext(self, next, s): # s表示模式串# 初始化j = -1next[0] = jfor i in range(1, len(s)): # 注意i從1開始 因為要比較 i 和 j是否相同# 前后綴不相同 while j>=0 and s[i]!=s[j+1]:j = next[j] # j回退# 前后綴相同if s[i]==s[j+1]:j += 1 # i和j都加1next[i] = j# 第二步 求下標索引def strStr(self, haystack, needle):""":type haystack: str:type needle: str:rtype: int"""if not needle:return 0next = [0]*len(needle) # 初始化nextself.getNext(next, needle)j = -1for i in range(len(haystack)):while j >= 0 and haystack[i]!=needle[j+1]: # j+1是因為j初始值為-1j = next[j] # next數(shù)組起作用了 找下一個匹配的位置if haystack[i]==needle[j+1]: # 匹配到字符相同j += 1# 判斷在文本串里出現(xiàn)了模式串if j == len(needle) - 1:return i - len(needle) + 1 # 返回索引return -1
暴力法
class Solution(object):def strStr(self, haystack, needle):""":type haystack: str:type needle: str:rtype: int"""m, n = len(haystack), len(needle)for i in range(m):if haystack[i:i+n] == needle:return ireturn -1
使用index(寫算法題不推薦)
class Solution:def strStr(self, haystack: str, needle: str) -> int:try:return haystack.index(needle)except ValueError:return -1
使用find(寫算法題不推薦)
class Solution:def strStr(self, haystack: str, needle: str) -> int:return haystack.find(needle)