28. Implementing strStr()
Answer:
- from
i = 0
toi = haystack.length - needle.length
traversehaystack
. - from
i
Start by judging one by oneneedle.length
Length of characters, whether each character is matched withneedle
Is the same as the character, if yes, it means foundneedle
To return toi
.
/ * * *@param {string} haystack
* @param {string} needle
* @return {number}* /
var strStr = function (haystack, needle) {
// Iterate over haystack and make sure to find a needle. Length string starting from I
for (let i = 0; i <= haystack.length - needle.length; i++) {
let judge = true // Determine if there is a string equal to needle
// Start with I and compare the needle. Length characters
for (let j = 0; j < needle.length; j++) {
If there are unequal characters, there must be no string equal to needle, exit the loop
if(needle[j] ! == haystack[i + j]) {// Set judge to false to avoid false judgments
judge = false
break}}// If it exits the loop normally, judge stays true, indicating that needle is found and the index is returned
if (judge) {
return i
}
}
// Exit loop, needle does not appear, return -1
return -1
}
Copy the code
- Or you can use
String.prototype.substr()
Method to capture a string for comparison.
/ * * *@param {string} haystack
* @param {string} needle
* @return {number}* /
var strStr = function (haystack, needle) {
// Iterate over haystack and make sure to find a needle. Length string starting from I
for (let i = 0; i <= haystack.length - needle.length; i++) {
// Select a needle. Length string from haystack
const sub = haystack.substr(i, needle.length)
// If sub is equal to needle, needle is found
if (sub === needle) {
return i
}
}
// Exit loop, needle does not appear, return -1
return -1
}
Copy the code