Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 154e34d

Browse files
implement-strstr()
1 parent ee608ed commit 154e34d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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"))
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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/>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /