Challenges • Asked over 5 years ago by rudebowski
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
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!