Reputation: 8593
I want to see it because there is an algorithm interview question asked similar thing but no one was able to resolve it without some sort of internal function like indexOf()
which would have been perfectly fine except that the requirement was NOT to use an internal function to resolve this.
Since I think the best implementation is already there, why don't I just learn from the best? Which I suppose is how they wrote .indexOf()
for String already in JavaScript.
My solution was humiliating to even show it... so I decide not to, in other words, there are way too much conditional toggling than I would want to put in there.
Thanks
Question is following
Avoid using built-in functions to solve this challenge. Implement them yourself, since this is what you would be asked to do during a real interview.
Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1.
Example
For s = "CodefightsIsAwesome" and x = "IA", the output should be strstr(s, x) = -1; For s = "CodefightsIsAwesome" and x = "IsA", the output should be strstr(s, x) = 10. Input/Output
[time limit] 4000ms (js) [input] string s
A string containing only uppercase or lowercase English letters.
Guaranteed constraints: 1 ≤ s.length ≤ 106.
[input] string x
String, containing only uppercase or lowercase English letters.
Guaranteed constraints: 1 ≤ x.length ≤ 106.
[output] integer
An integer indicating the index of the first occurrence of the string x in s, or -1 if s does not contain x
Bitw its from codefight https://codefights.com/interview-practice/task/C8Jdyk3ybixqQdAvM
For anyone interested to test their code in full with all test cases, its here (see where my cursor is pointing to in the image vvv?)
https://codefights.com/interview-practice/topics/strings
Upvotes: 3
Views: 2909
Reputation: 24181
no one was able to resolve it
I'm a little shocked that was the case, as it's just 2 simple nested for loops. Eg, it took me less than a few minutes to knock this up.
function strstr(a,b) {
for (var o = 0; a[o]; o ++)
{
var found = true;
for (var i = 0; b[i]; i ++) {
if (a[o + i] !== b[i]) { found=false; break; }
}
if (found) return o;
}
return -1;
}
var s = "CodefightsIsAwesome";
var x = "IA";
console.log(strstr(s, x));
s = "CodefightsIsAwesome";
x = "IsA";
console.log(strstr(s, x));
Upvotes: 6
Reputation: 1025
JavaScript runs on ECMAScript Engines. ECMAScript is nothing but the specification of JavaScript. Different browser provides different implementation for that, like Chrome has V8 engine implementation for ECMAScript, similarly Carakan for Opera. Source
So with that in mind... Here you might get some more information on how things work:
General MDN entry: Click
Upvotes: 1