今天是紀錄LeetCode解題的第二十八天
第二十八題題目: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.
給定兩個字串haystack和needle,回傳needle在haystack中出現的第一個索引,如果不存在則回傳-1
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
#return haystack.find(needle)
result = -1
for i in range(len(haystack)):
if haystack[i:i+len(needle)] == needle:
result = i
break
return result
python提供find函數可以直接找到needle出現的第一個索引位置,另一種方式是遍歷hatstack,找i~i+len(needle)長度的字串,相等就代表needle存在於hatstack裡,此時i就等於第一個出現的索引位置。ps:這題太簡單了不多做說明