28. 实现 strStr() (本题可以跳过)
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
暴力解题 对haystack每一位进行循环 比较是否把其作为开始的单词和needle进行比较 有就是true,退出loop时说明没有 return false
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
ns=len(haystack)
nn=len(needle)
for i in range(ns):
if haystack[i:i+nn]==needle:
return i
return -1
459.重复的子字符串 (本题可以跳过)
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
如果是一个repeat pattern的话 那它就是一个substr的repetition, 按照这个思路去寻找是否有substr的repetition等于s。注意我们for循环不需要跑完 因为repeat至少需要两个substr组成 同时注意开始的index是1不是0。判断substr的repetition等于s的同时也要注意字符长度n%i==0.
class Solution(object):
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
n=len(s)
for i in range(1,n//2+1):
if n%i==0 and s[:i]*(n//i)==s:
return True
return False
Time complexity: O(n*sqrt(n)) dvisors of n must be less than O(sqrt(n)).
Space compexity:O(n)
文章介绍了两道编程题的解题思路。第一题strStr()使用暴力方法检查haystack中是否存在needle,返回首次出现的索引或-1。第二题检查给定字符串s是否有重复的子字符串,通过测试字符串的子串重复性来确定答案。时间复杂度与空间复杂度也进行了讨论。
871

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



