題目描述:

題解1:
直接利用find函數尋找子串開始位置,不存在則傳回-1,為空的特殊情況傳回0
def strStr(self, haystack, needle):
if needle=="":
return 0
index = haystack.find(needle)
return index
題解2:
周遊haystack字元串,如果在某個位置i與needle中第一個字元相同,則從該位置開始比對,完全相同則傳回i,否則傳回-1
def strStr(self, haystack, needle):
len1 = len(haystack)
len2 = len(needle)
if needle=="":
return 0
for i in range(len1-len2+1):
count = 0
if haystack[i]==needle[0]:
for j in range(len2):
if haystack[i+j]==needle[j]:
count=count+1
if count==len2:
return i
return -1