28. Find the Index of the First Occurrence in a String
题目 :
给2个字串needle和haystack,
回传needle第一次出现在haystack中的index,
如果needle不在haystack中则回传-1
Example 1:
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.
思路 :
for循环跑haystack
找到第一个字母符合的就比对一下
=================================
python code :
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
len_needle = len(needle)
for i in range(len(haystack)) :
if haystack[i] == needle[0] :
if i+len_needle-1 < len(haystack) :
if haystack[i:i+len_needle] == needle :
return i
return -1
python直接可以[i:i+长度]比对起来比较方便
其他语言应该不太能这样写??
但我看这题related topic有two pointer
不过不太懂要怎么用two pointer
有大师要解惑吗??