代码随想录算法训练营第九天 | 28. 找出字符串中第一个匹配项的下标,459.重复的子字符串
28-找出字符串中第一个匹配项的下标
题目:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1: 输入: haystack = “hello”, needle = “ll” 输出: 2
示例 2: 输入: haystack = “aaaaa”, needle = “bba” 输出: -1
题目链接:28-找出字符串中第一个匹配项的下标
思路:
先建立next数组,再将两个字符串一起比较。
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# m, n = len(haystack), len(needle) 暴力解法
# for i in range(m):
# if haystack[i:i+n] == needle:
# return i
# return -1
a, b = len(needle), len(haystack)
if a == 0:
return 0
next = self.getnext(a, needle)
p = -1
for j in range(b): #寻找开始匹配的字符
while p >= 0 and needle[p+1] != haystack[j]:
p = next[p]
if needle[p+1] == haystack[j]:
p += 1
if p == a-1:
return j-a+1
return -1
def getnext(self, a, needle): #建立next数组
next = ['' for i in range(a)]
k = -1
next[0] = k
for i in range(1, len(needle)):
while (k > -1 and needle[k+1] != needle[i]):
k = next[k]
if needle[k+1] == needle[i]:
k += 1
next[i] = k
return next
459-重复的子字符串
题目:
给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。
示例 1:
输入: “abab”
输出: True
解释: 可由子字符串 “ab” 重复两次构成。
题目链接:459-重复的子字符串
思路:
1.构建next数组,
2.由于数组长度减去最长相同前后缀的长度相当于是第一个周期的长度,也就是一个周期的长度,如果这个周期可以被整除,就说明整个数组就是这个周期的循环。
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
if len(s) == 0:
return False
next = [0] * len(s)
self.getnext(next, s)
if next[-1] != -1 and len(s) % (len(s) - (next[-1] + 1)) == 0:
return True
return False
def getnext(self, next, s):
next[0] = -1
k = -1
for i in range(1, len(s)):
while (k >= 0 and s[i] != s[k+1]): # k从位置-1开始
k = next[k]
if s[i] == s[k+1]:
k += 1
next[i] = k
return next
总结:
对next数组的构建和使用还需要多复习复习。这两题的做法还是有点难理解。