Image From LeetCodeImage From LeetCode

今天我們要講解的是 [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
2
3
4
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.
1
2
3
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.

Constraints:

  • 1 <= haystack.length, needle.length <= 104
  • haystack and needle consist of only lowercase English characters.

自已解法

這個題目主要是針對haystack來檢查是第一個index才與needle相同,首先我們先建立lenoutput的值。

1
2
3
4
5
6
var strStr = function(haystack, needle) {
let len = needle.length;
let output = -1;

return output;
};

接著我們針對haystack去跑迴圈,另外避免白跑,我們需要在i < (size - len + 1)之前直接結束,接著透過slice進行字串切割來進行比對,正確我們就可以直接跳脫並寫入output值。

1
2
3
4
5
6
7
8
9
10
11
var strStr = function(haystack, needle) {
let len = needle.length;
let output = -1;
for(let i = 0; i < haystack.length - len + 1; i++) {
if (haystack.slice(i, i + len) === needle) {
output = i;
break;
}
}
return output;
};

實作結果

以上就是這次的實作,感謝各位!

Image From LeetCodeImage From LeetCode