Day08–1209刷题:字符串–28. 实现 strStr(),459. 重复的子字符串
| 题目 | 用时 |
|---|---|
| 28. 实现 strStr() | 3min33s |
| 459. 重复的子字符串 | * |
28. 实现 strStr()(找出字符串中第一个匹配项的下标)
[!NOTE]
给你两个字符串
haystack和needle,请你在haystack字符串中找出needle字符串的第一个匹配项的下标(下标从 0 开始)。如果needle不是haystack的一部分,则返回-1。
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
len_n = len(needle)
for i in range(len(haystack)):
if haystack[i:i+len_n] == needle:
return i
return -1
这个方法似乎很水,似乎要用KMP算法才是比较高级的思路
459. 重复的子字符串
[!NOTE]
给定一个非空的字符串
s,检查是否可以通过由它的一个子串重复多次构成。
先马住,慢慢看,好难理解
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] != -1 and len(s) % (len(s) - (nxt[-1] + 1)) == 0:
return True
return False
def getNext(self, 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

818

被折叠的 条评论
为什么被折叠?



