Community

Start a Thread


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

Would this not be a simpler solution?

Challenges • Asked over 4 years ago by rudebowski

rudebowski Commented on Jul 23, 2019:

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

js
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:

js
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

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!