28.找出字符串中第一个匹配项的下标
题目链接: https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
思路:暴力了
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
x = len(haystack)
y = len(needle)
if x == 0 or y > x:
return -1
if y == 0:
return 0
for i in range(x-y+1):
if haystack[i] == needle[0]:
if haystack[i:i+y] == needle:
return i
return -1
459.重复的子字符串
题目链接: https://leetcode.cn/problems/repeated-substring-pattern/
实话 KMP我还得研究 不是特别懂
def go_next(nxt, s):
nxt[0] = -1
j = -1
for i in range(1,len(s)):
while j >= 0 and s[i] != s[j+1]:
j = nxt[j]
if s[i] == s[j+1]:
j += 1
nxt[i] = j
return nxt
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
if len(s) == 0:
return False
nxt = [0] * len(s)
go_next(nxt, s)
if nxt[-1] != -1 and len(s)%(len(s)-(nxt[-1]+1)) == 0:
return True
return False