28. Find the Index of the First Occurrence in a String
Python find()
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
朴素解法
遍历,haystack中每个字母作为发起点
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 i
return -1
KMP
YouTube上这个视频讲得很清楚
意思明白,代码难写
。。。
# 2023年8月3日
# https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/solutions/2335848/javapython3wei-shi-yao-shi-kmptu-jie-by-p2d4b/
class Solution:
def getNext(self, next, needle):
for i in range(1, len(needle)):
k = next[i - 1]
while needle[i] != needle[k]:
if k == 0:
k -= 1 # 为了和最后的next[i] = k + 1匹配
break
else:
k = next[k - 1]
next[i] = k + 1
def strStr(self, haystack: str, needle: str) -> int:
next = [0] * len(needle)
self.getNext(next, needle)
i = 0 # 遍历haystack
j = 0 # 遍历needle
while i < len(haystack):
if haystack[i] == needle[j]:
i += 1
j += 1
elif j == 0:
i += 1 # needle第一个字符就开始不匹配
else:
j = next[j - 1]
if j >= len(needle):
return i - len(needle)
return -1
459. Repeated Substring Pattern
假设字符串S
可以被它的字串Sp
多次重复构成,那么可以表示为S = SpSp
,
若将两个S
拼接,则SS = SpSpSpSp
.
通过去除SS
首尾的两个字符,可以得新的SS2 = SxSpSpSy
.
SS2
中应包含S
.
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
t = s + s
if t.find(s, 1, len(t)-1) != -1:
return True
else:
return False