實現strStr
實現 strStr() 函數。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
解決方法:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
L, N = len(haystack), len(needle)
for i in range(L-N+1):
# 將needle整個去和haystack進行匹配
if haystack[i:len(needle)+i] == needle:
return i
return -1