Community

Ask A Question


Notifications
Subscribe You’re not receiving notifications from this thread.

Would this not be a simpler solution?

Challenges • Asked 6 months ago by rudebowski

Gravatar rudebowski Commented on Jul 23, 2019:

For the detect substring in a string problem, here was the solution offered:

        function detectSubstring(str, subStr) {
            let idxOfStart = 0,
                j = 0;

            for (i = 0; i < str.length; i++) {
                // if match, compare next character of subStr with next of string
                if (str[i] == subStr[j]) {
                    j++;
                    if (j == subStr.length) {
                        return i - (subStr.length - 1);
                    }
                } else {
                    i -= j;
                    j = 0;
                }
            }

            return -1;
        }

Here was my solution:

        function detectSubstring(str, subStr) {
            for (let i = 0; i < str.length - subStr.length; i++) {
                if (str.substring(i, i+subStr.length) === subStr) return i;
            }
            return -1;
        }

Is there any advantage to using the more verbose version? I don't really know whether mine would be inherently slower or something

Gravatar Jake from AlgoDaily Commented on Jul 27, 2019:

Hey rudebowski,

The point of the exercise was to avoid using the substring method, and to come up with it on your own. I'll edit the challenge to make that clearer!

Terms and Conditions | Privacy