gpt4 book ai didi

javascript - 我应该在哪里找到 indexOf 函数是如何为 JavaScript 核心编写的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:52:19 32 4
gpt4 key购买 nike

我想看它,因为有一个算法面试问题问了类似的事情,但如果没有像 indexOf() 这样的内部函数,没有人能够解决它,除了要求不是使用内部函数来解决这个问题。既然我认为最好的实现已经存在,为什么我不直接向最好的实现学习呢?我想这就是他们如何为已经在 J​​avaScript 中的字符串编写 .indexOf()

我的解决方案甚至展示它都让人感到羞辱...所以我决定不这样做,换句话说,有太多的条件切换比我想放在那里的要多。

谢谢

问题如下

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

对于任何有兴趣使用所有测试用例完整测试其代码的人,请点击此处(查看我的光标在图像 vvv 中指向的位置?)

https://codefights.com/interview-practice/topics/strings enter image description here

最佳答案

no one was able to resolve it

我对这种情况感到有点震惊,因为它只是 2 个简单的嵌套 for 循环。例如,我花了不到几分钟的时间就完成了。

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));

关于javascript - 我应该在哪里找到 indexOf 函数是如何为 JavaScript 核心编写的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46731372/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com