Implement strStr()


我用JS刷LeetCode | Day 9 | Implement strStr()

刪除排序數組中的重複項:

說明:現階段的解題暫未考慮複雜度問題

Question:

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

中文題目:

實現 strStr() 函數。

給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從 0 開始)。如果不存在,則返回 -1。

說明:

當 needle 是空字符串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。

對於本題而言,當 needle 是空字符串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。

Example:

<code>Input: haystack = "hello", needle = "ll"
Output: 2
Input: haystack = "aaaaa", needle = "bba"
Output: -1

/<code>

個人分析:

  1. 看到題目第一想法, 可以使用 indexOf,於是得到 答案一。
  2. 分享幾個其他答案:你有想到將輸入的 haystack 以 needle 為分隔符,轉換成字符串嗎?轉換成的數組的第一個元素的長度,就是我們需要的找的字符串出現的第一個位置,於是得到 答案二.
  3. 當 needle 和 haystack 相等,或者 needle 為空,則直接返回 0。然後 遍歷 haystack, 當 haystack 中出現某個元素與 needle 中第一個元素相等時,利用 substring 方法,從當前元素開始,在 haystack中截取 neddle 長度的字符串,比較截取的值是否和 needle 相等,若相等,當前元素的索引即為所求的值,否則返回 -1,於是得到 答案三。

Answer:

<code>// 答案一
var strStr = function(haystack, needle) {
return haystack.indexOf(needle)
};
//答案二
var strStr = function(haystack, needle) {
if (needle === '') return 0;
const split = haystack.split(needle);
return split.length > 1 ? split[0].length : -1;
};
// 答案三
var strStr = function(haystack, needle) {
if (haystack === needle || needle === "") {
return 0;
}

for (let i = 0; i < haystack.length; i++) {
if (haystack[i] === needle[0]) {
let temp = haystack.substring(i, i + needle.length);
if (temp === needle) {
return i;
}
}
}
return -1;
};
/<code>

其他:

本題更多 JavaScript 解析,點擊「瞭解更多」,文章底部查看更多答案。

我用JS刷LeetCode | Day 9 | Implement strStr()


我用JS刷LeetCode | Day 9 | Implement strStr()


分享到:


相關文章: