-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrStr.js
More file actions
52 lines (44 loc) · 1.42 KB
/
strStr.js
File metadata and controls
52 lines (44 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 28. Implement strStr()
// Easy
// Implement strStr().
// Return the index of the first occurrence of needle in haystack, or - 1 if needle is not part of haystack.
// Example 1:
// Input: haystack = "hello", needle = "ll"
// Output: 2
// Example 2:
// Input: haystack = "aaaaa", needle = "bba"
// Output: -1
// Solution I
// const strStr = (haystack, needle) => (haystack.indexOf(needle))
// Solution II
// 思路 不断切相同长度的子串下来进行比较,直到主串长度不够
const strStr = (haystack, needle) => {
const haystackLen = haystack.length
const needleLen = needle.length
for (let i = 0; i <= haystackLen - needleLen; i++) {
// const slicedStr = haystack.slice(i, i+needleLen)
const slicedStr = haystack.subStr(i, needleLen)
if (slicedStr == needle) return i
}
return -1
}
// Solution III
var strStr = function (haystack, needle) {
if (needle === '') return 0
if (needle.length > haystack.length) return -1
if (haystack == needle) return 0
for (let i = 0; i < haystack.length; i++) {
// 找到每个匹配的位置
if (haystack[i] === needle[0]) {
if (needle.length == 1) return i
// 看子串剩余部分是否也匹配
let t = i + 1
for (let j = 1; j < needle.length; j++ , t++) {
if (haystack[t] !== needle[j]) break //return -1
if (j == needle.length - 1) return t - j
}
}
}
return -1
};
//tip: JS + string 可以切啊