28.实现 strStr()
题目链接
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
视频讲解
帮你把KMP算法学个通透!(理论篇)_哔哩哔哩_bilibili
帮你把KMP算法学个通透!(求next数组代码篇)_哔哩哔哩_bilibili
笔记
- 偷懒了,KMP算法留到下次学
- Python字符串的find(str)方法在字符串中查找str,如果能找到返回开始下标,找不到返回-1
- index(str)和find(str)一样,只不过如果str不在字符串中会报一个异常,需要在外面加try语句
Python代码
# find(str)方法
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
# index(str)方法
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
try:
return haystack.index(needle)
except ValueError:
return -1
459.重复的子字符串
题目链接
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
视频讲解
字符串这么玩,可有点难度! | LeetCode:459.重复的子字符串_哔哩哔哩_bilibili
笔记
- KMP算法再次偷懒,下次学
- 另一个思路是:如果s是由重复子串构成,那么s+s中间一定能找出一个s,但要注意找中间s的时候要把s+s的首位字符去掉,否则就有可能找到原本的两个s。
Python代码
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
double_s = s + s
tmp = double_s[1:len(double_s)-1].find(s)
if tmp == -1:
return False
else:
return True