LeetCode28。 strStr()JavaScriptを実装する



Leetcode28 Implement Strstr Javascript



達成strStr()関数。

与えられたa haystack文字列と1つneedle文字列、in haystack文字列で調べるneedle文字列が表示される最初の位置(from 0 Start)。存在しない場合は、-1を返します。



例1:

入力:haystack = 'hello'、needle = 'll'出力:2



例2:

入力:haystack = 'aaaaa'、needle = 'bba'出力:-1

説明:when needle空の文字列の場合、どの値を返す必要がありますか?これはインタビューで非常に良い質問です。この質問の場合、いつneedle空の文字列0の場合に戻る必要があります。これはC言語ですstrstr()そしてJava indexOf()定義が一致します。



回答参照:

/** * @param {string} haystack * @param {string} needle * @return {number} */ var strStr = function(haystack, needle) { / / Determine whether the query string is empty if (!needle) { return 0 } / / Call the indexOf function to return the position of the substring return haystack.indexOf(needle) } Copy code