1-
2- /**
3- * 28. Implement strStr()
4- * Difficulty:Easy(459延伸題)
5- *
6- * Implement strStr().
7- *
8- * Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
9- *
10- * Clarification:
11- * What should we return when needle is an empty string? This is a great question to ask during an interview.
12- * 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().
13- *
14- * ---------------------------------------------------
15- * Input: haystack and needle are string
16- * Output:在haystack中第一個出現的needle index值
17- * 若haystack沒有needle,return -1;
18- * 或needle是空的,return 0
19- * ------------------------------------------------------
20- * Example 1:
21- * Input: haystack = "hello", needle = "ll"
22- * Output: 2
23- *
24- * Example 2:
25- * Input: haystack = "aaaaa", needle = "bba"
26- * Output: -1
27- *
28- * Example 3:
29- * Input: haystack = "", needle = ""
30- * Output: 0
31- *
32- * Constraints:
33- * 0 <= haystack.length, needle.length <= 5 * 104
34- * haystack and needle consist of only lower-case English characters.
35- */
361/**
2+ * 28. Find the Index of the First Occurrence in a String
3+
4+ * 回傳needle第一次出現在haystack的index,找不到回傳-1
5+ *
376 * @param {string } haystack
387 * @param {string } needle
398 * @return {number }
409 */
41- var strStr = function ( haystack , needle ) {
42- /**
43- * haystack中:
44- * 有needle,return haystack index
45- * 沒有,return -1
46- * $haystack或$needle是空,retunr 0
47- *
48- * $haystack、$needle 都是英文小寫
49- */
50-
51- if ( needle === "" ) {
52- return 0 ;
53- }
54- for ( let i = 0 ; i < haystack . length ; i ++ ) {
55-
56- // Return part of string:
57- // for JS: string.substr(start,end)
58- // for PHP: substr(string,start,end)
59- let slice = haystack . substr ( i , needle . length ) ;
60- if ( slice === needle ) {
61- return i ;
62- }
63- }
64- return - 1 ;
65-
10+ var strStr = function ( haystack , needle ) {
11+ return haystack . indexOf ( needle ) ;
6612} ;
67- let h = "hello" ;
68- let nee = "ll" ;
69- // 2
70- console . log ( strStr ( h , nee ) ) ;
13+ // let haystack = "leetcode", needle = "leeto";
14+ // -1
15+ let haystack = "sadbutsad" , needle = "sad" ;
16+ // 0
17+ console . log ( strStr ( haystack , needle ) ) ;
0 commit comments