题目:
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
For the purpose of this problem, we will return 0 when needle is an empty string.
给定两个字串(haystack,needle),检查needle是否在haystack内,若有回传needle第一次出现时的index,若无则回传-1,若needle为空,回传0
用一些字串操作,这题会变得十分简单
class Solution: def strStr(self, haystack: str, needle: str) -> int: if needle not in haystack: return -1 if needle=="": return 0 haystack=haystack.replace(needle," ") for i in range(len(haystack)): if haystack[i]==" ": return i
先检测needle是否在haystack内及needle是否为空字串
确定needle在haystack内后将needle replace成" "
最后再检索" "的位置即可
最后执行时间为28ms(faster than 96.18%)
但这样似乎有点偷吃步
在讨论区有看到比较正规的解法
class Solution: def strStr(self, haystack: str, needle: str) -> int: if needle=="": return 0 for i in range(len(haystack)-len(needle)+1): if haystack[i:i+len(needle)]==needle: return i return -1
简单来说就是偏暴力解,一个一个去对比
不过最后执行时间为31ms(faster than 91.34%),也不算太差
大概分享一下其他写法
那我们下题见