自己写的
class Solution: def strStr(self, haystack: str, needle: str) -> int: haystack_len = len(haystack) needle_len = len(needle) if haystack == needle: return 0 if haystack_len < needle_len: return -1 i = 0 while i <= haystack_len - needle_len: if haystack[i] == needle[0]: # 遍历haystack如果和needle第一个相同就开始对比 if needle_len==1: return i j = 1 while j < needle_len: if haystack[i + j] == needle[j]: j += 1 if j == needle_len: return i else: i += 1 if i == haystack_len - needle_len + 1: return -1 break else: # 遍历haystack如果和needle第一个不相同就下一个 i += 1 if i == haystack_len - needle_len + 1: return -1
gpt回答
class Solution: def strStr(self, haystack: str, needle: str) -> int: haystack_len = len(haystack) needle_len = len(needle) if needle_len == 0: return 0 for i in range(haystack_len - needle_len + 1): if haystack[i:i + needle_len] == needle: return i return -1
class Solution: def strStr(self, haystack: str, needle: str) -> int: haystack_len = len(haystack) needle_len = len(needle) if needle_len == 0: return 0 for i in range(haystack_len - needle_len + 1): # 截取 haystack 中与 needle 长度相同的子串 current_substring = haystack[i:i + needle_len] # 检查子串是否与 needle 相等 if current_substring == needle: return i # 如果没有找到匹配,返回 -1 return -1
标签:下标,int,needle,leedcode,len,str,字符串,return,haystack From: https://www.cnblogs.com/yyyjw/p/17980265