This is the 12th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge;

This is the force buckle series 4, today and friends together punch punch buckle problem 28: strStr().

1. Description of the topic

Implement the strStr() function.

Given the two strings haystack and Needle, find the first place in the haystack string where the needle string appears (subscript starting from 0). If it does not exist, return -1.

Description:

What value should we return when needle is an empty string? This is a good question to ask in an interview.

For this case, we should return 0 when needle is an empty string. This is consistent with the C language’s STRSTR () and Java’s indexOf() definitions.

Example 1:

Input: haystack = "hello", needle = "ll" Output: 2Copy the code

Example 2:

Input: haystack = "aaaaa", needle = "bba" Output: -1Copy the code

Example 3:

Input: haystack = "", needle = "" Output: 0Copy the code

Tip:

  • 0 <= haystack.length, needle.length <= 5 * 104
  • Haystack and needle consist only of lowercase English characters

Source: LeetCode link: leetcode-cn.com/problems/im… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Second, thinking analysis

Get this topic, you can judge first, if the string to find is empty, then directly return 0, if not empty then continue to execute.

Define two constants n and m, representing the length of the needle and the length of the needle, respectively, and write a for loop starting from 0. The loop satisfies the condition that the current subscript plus the total length of the string to be searched is less than or equal to the total length of all characters, that is, I + m <= n.

Define a variable flag as true in the loop, and then write a loop in the loop to determine whether the values of the two items are equal. If they are not equal, set flag to false, jump out of the loop body, and return -1. Otherwise, when you get the index, you just go back.

Three, JavaScript implementation code

/ * * *@param {string} Haystack All characters are *@param {string} Needle Specifies the character to look for@return {number} The subscript * /
var strStr = function (haystack, needle) {
    if (needle.length === ' ') {
        return 0;
    }
    const n = haystack.length, m = needle.length;
    for (let i = 0; i + m <= n; i++) {
        let flag = true;
        for (let j = 0; j < m; j++) {
            if(haystack[i + j] ! = needle[j]) { flag =false;
                break; }}if (flag) {
            returni; }}return -1;
};
Copy the code

Four,

The front is a long distance, we are all on the road, hope to communicate with friends, progress together. Keep updating ing…..