面试题:实现字符串的indexOf

128 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第2天,点击查看活动详情

乍看之下,觉得这道题很简单,所以indexOf就是返回b字符串在a字符串中的位置,如果不存在返回-1呗。 但是真的有这么简单吗。

首先看一下indexOf的API

str.indexOf(searchValue [, fromIndex])

其中,str是被查找字符串,searchValue是需要查找的字符串,还有一个可选参数起始位置

我们现在开始实现

假设这个函数叫MyIndexOf,它有3个参数fatherStr,childStr,n

function MyIndexOf(fatherStr,childStr,n){}

1.首先我们先判断这个可选参数,如果它不存在或者不是数字,就直接设置为0

 let i = 0
if(n&&typeof n === 'number'){
    i=n
} else {
    i=0
}

2.其次,我们再提前判断一些简单的情况,优先返回,提高速度 例如:当子串长度大于父串的时候

const faterLength = fatherStr.length
const childLength = childStr.length
if(childLength > faterLength){
    return -1
} else if(faterLength === childLength) {
    return  fatherStr === childStr ? 0 : -1
} else {
  //需要遍历去对比
}

3.现在看一下遍历的时候

我采用的办法是截取父串,于子串去做对比.这里还有其他办法,大家可以集思广益

let temp=''
while(i<faterLength){
    temp=fatherStr.substr(i,childLength);
    if(temp==childStr){
        return i;
    }
    i++;
}
if(i===faterLength){
    return -1;
}

总结

image.png