File tree Expand file tree Collapse file tree 2 files changed +47
-0
lines changed
easy/0028 implement-strstr() Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } haystack
3
+ * @param {string } needle
4
+ * @return {number }
5
+ */
6
+ var strStr = function ( haystack , needle ) {
7
+ if ( needle . length == 0 || needle == null ) return 0 ;
8
+
9
+ for ( let i = 0 ; i < haystack . length - needle . length + 1 ; i ++ ) {
10
+ let j = 0 ;
11
+ while ( j < needle . length ) {
12
+ if ( haystack [ i + j ] != needle [ j ] )
13
+ break ;
14
+ j ++ ;
15
+ }
16
+ if ( j >= needle . length )
17
+ return i ;
18
+ }
19
+ return - 1 ;
20
+ } ;
21
+
22
+ // var strStr = function (haystack, needle) {
23
+ // return haystack.indexOf(needle)
24
+ // };
25
+
26
+ console . log ( strStr ( "hello" , "ll" ) )
Original file line number Diff line number Diff line change
1
+ # implement-strstr()
2
+
3
+ Implement strStr().
4
+
5
+ Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
6
+
7
+ ## Example 1
8
+
9
+ Input: haystack = "hello", needle = "ll"
10
+
11
+ Output: 2
12
+
13
+ ## Example 2
14
+
15
+ Input: haystack = "aaaaa", needle = "bba"
16
+
17
+ Output: -1
18
+
19
+ ## More Info
20
+
21
+ < https://leetcode.com/problems/implement-strstr/ >
You can’t perform that action at this time.
0 commit comments