Leetcode 28 Find the Index of the First Occurrence in a String
- 题目链接:leetcode.com/problems/fi…
- 文章讲解:代码随想录 programmercarl.com
- 视频讲解:帮你把KMP算法学个通透!(理论篇)帮你把KMP算法学个通透!(求next数组代码篇)
- 状态:有做出来
1. 第一想法
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n = len(haystack)
m = len(needle)
start = n-m
if start == 0:
if haystack == needle:
return 0
for i in range(start + 1):
p1 = i
p2 = 0
while haystack[p1] == needle[p2]:
p1 += 1
p2 += 1
if p2 == len(needle):
return i
return -1
2. 看完后想法
class Solution:
def getNext(self, next: list[int], s: str) -> None:
j = 0
next[0] = 0
for i in range(1, len(s)):
while j > 0 and s[i] != s[j]:
j = next[j-1]
if s[i] == s[j]:
j += 1
next[i] = j
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
next = [0] * len(needle)
self.getNext(next, needle)
j = 0
for i in range(len(haystack)):
while j > 0 and haystack[i] != needle[j]:
j = next[j-1]
if haystack[i] == needle[j]:
j += 1
if j == len(needle):
return i - len(needle) + 1
return -1
3. 总结
常看常新。
Leetcode 459 Repeated Substring Pattern
- 题目链接:leetcode.com/problems/re…
- 文章讲解:代码随想录 programmercarl.com
- 视频讲解:字符串这么玩,可有点难度! | LeetCode:459.重复的子字符串
- 状态:没做出来
1. 第一想法
怎么找 substring 呢。
2. 看完后想法
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
if len(s) == 0:
return False
nxt = [0] * len(s)
self.getNext(nxt,s)
if nxt[-1] != 0 and len(s) % (len(s) - nxt[-1]) == 0:
return True
return False
def getNext(self, nxt, s):
nxt[0] = 0
j = 0
for i in range(1, len(s)):
while j > 0 and s[i] != s[j]:
j = nxt[j-1]
if s[i] == s[j]:
j += 1
nxt[i] = j
return nxt
3. 总结
常看常新。