Skip to content

Commit 6d30076

Browse files
committed
Implement strStr()
1 parent 0fa0cea commit 6d30076

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
|9|[回文数](https://leetcode-cn.com/problems/palindrome-number/)|[JavaScript](./algorithms/palindrome-number.js)|Easy|
99
|14|[最长公共前缀](https://leetcode-cn.com/problems/longest-common-prefix/)|[JavaScript](./algorithms/longest-common-prefix.js)|Easy|
1010
|21|[合并两个有序链表](https://leetcode-cn.com/problems/merge-two-sorted-lists/)|[JavaScript](./algorithms/merge-two-sorted-lists.js)|Easy|
11+
|28|[实现 strStr()](https://leetcode-cn.com/problems/implement-strstr/)|[JavaScript](./algorithms/implement-strstr.js)|Easy|
1112
|66|[加一](https://leetcode-cn.com/problems/plus-one/)|[JavaScript](./algorithms/plus-one.js)|Easy|
1213
|136|[只出现一次的数字](https://leetcode-cn.com/problems/single-number/)|[JavaScript](./algorithms/single-number.js)|Easy|
1314
|189|[轮转数组](https://leetcode-cn.com/problems/rotate-array/)|[JavaScript](./algorithms/rotate-array.js)|Medium|

algorithms/implement-strstr.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// 暴力破解
2+
3+
/**
4+
* 实现 strStr()
5+
* @param {string} haystack
6+
* @param {string} needle
7+
* @return {number}
8+
*/
9+
var strStr = function(haystack, needle) {
10+
if (!needle) {
11+
return 0
12+
}
13+
14+
for (let i = 0; i < haystack.length; i++) {
15+
if (haystack.slice(i, i + needle.length) === needle ) {
16+
return i
17+
}
18+
}
19+
20+
return -1
21+
};
22+
23+
// KMP
24+
// 以后补充

0 commit comments

Comments
 (0)