昨天太晚才做出來這一題,所以就懶得寫下來了
Leetcode 28
28. Find the Index of the First Occurrence in a String
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
.
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.
Constraints:
1 <= haystack.length, needle.length <= 10
4
haystack
andneedle
consist of only lowercase English characters.
我最初寫法 :

- 若
needle
不在haystack
中,輸出-1
- 找出
haystack
中和needle[0]
一樣的字母的位置號碼,將它們變成字串 - 利用
for
迴圈,針對temp
的位置號碼,比較haystack
和needle
是否一樣
EX:
輸入:
haystack =
"mississippi"
needle =
"sipp"
正確輸出:
6
我的想法 :
temp =[2, 3, 5, 6]
for迴圈中 :
將字串temp轉成int()型態
item依序跑2、3、5、6
從haystack[2]開始跑
haystack[2] = needle[0],item= item + 1 = 2 + 1 = 3
haystack[3] != needle[1],break出內層for迴圈
接著從haystack[3]繼續跑
haystack[3] = needle[0],item= item + 1 = 3 + 1 = 4
haystack[4] = needle[1],item= item + 1 = 4 + 1 = 5
haystack[5] != needle[2],break出內層for迴圈
接著從haystack[5]繼續跑
haystack[5] = needle[0],item= item + 1 = 5 + 1 = 6
haystack[6] !=needle[1],break出內層for迴圈
接著從haystack[6]繼續跑
haystack[6] = needle[0],item= item + 1 = 6 + 1 = 7
haystack[7] = needle [1],item= item + 1 = 7 + 1 = 8
haystack[8] = needle[2],item = item + 1 = 8 + 1 = 9
haystack[9] = needle[3]
完整跑完的haystack[6],最後輸出 6
其實這題還可以用slicing strings 的寫法去做
會快很多
之後再來寫~~