LeetCode - Find The Index Of The First Occurrence In A String
今天我們要講解的是 [Find The Index Of The First Occurrence In A String],這在 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.
Example
1 | Input: haystack = "sadbutsad", needle = "sad" |
1 | Input: haystack = "leetcode", needle = "leeto" |
Constraints:
1 <= haystack.length, needle.length <= 104haystackandneedleconsist of only lowercase English characters.
自已解法
這個題目主要是針對haystack來檢查是第一個index才與needle相同,首先我們先建立len與output的值。
1 | var strStr = function(haystack, needle) { |
接著我們針對haystack去跑迴圈,另外避免白跑,我們需要在i < (size - len + 1)之前直接結束,接著透過slice進行字串切割來進行比對,正確我們就可以直接跳脫並寫入output值。
1 | var strStr = function(haystack, needle) { |
實作結果
以上就是這次的實作,感謝各位!

