Sunny-117/js-challenges

实现一个字符串匹配算法indexOf

Sunny-117 opened this issue · 8 comments

实现一个字符串匹配算法indexOf
function myIndexOf(str1,str2) {
    if (str2.length <= 0) return -1
    const shortStr = str1.length >= str2.length ? str2 : str1
    const longStr = shortStr  === str1 ? str2 : str1
    firstChar = shortStr[0]
    let left = 0 
    for (var i = 0; i < longStr.length; i++) {
        left = longStr[i] === firstChar ? i : left
        // console.log(typeof longStr)
        if (longStr.substr(left,shortStr.length) === shortStr) return left 
    }
    return -1
}

console.log(myIndexOf('zhpp','pp')); // 2

具体实现可能不够精简,但是应该更加符合原indexOf的参数要求

// 实现字符串匹配indexOf方法
// string.indexOf(searchvalue,start)
//        searchvalue:必需。规定需检索的字符串值。
//        start:可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 string Object.length - 1。
//              如省略该参数,则将从字符串的首字符开始检索。
String.prototype.indexOf = function myIndexOf(searchvalue, start = 0) {
    console.log("myIndexOf");
    if (typeof searchvalue !== "string") throw TypeError("需检索值非字符串");
    if (start < 0 || start > this.length)
      throw TypeError(
        "开始检索的位置取值不合法,合法取值是 0 到 string.length - 1"
      );
    for (let index = start; index < this.length; index++) {
      if (this[index] === searchvalue[0]) {
        let len = searchvalue.length;
        let i = 0;
        while (i < len && this[index + i] === searchvalue[i]) {
          // console.log("this[index + i]", this[index + i], searchvalue[i]);
          i++;
        }
        // console.log(i);
        if (i === len) return index;
      }
    }
  };
  
  str = "test tesy";
  console.log(str.indexOf("t"));
  
gto999 commented
function indexOf(string, substring) {
  if (substring === "") {
    return -1;
  }

  for (var i = 0, len= string.length; i < len; i += 1) {
    if (string.slice(i, i + substring.length) === substring) {
      return i;
    }
  }

  return -1;
}
function indexOf(string, subString = "undefined", startIndex = 0) {
    subString = String(subString)

    startIndex = Number.isInteger(startIndex) ? startIndex : 0
    startIndex = startIndex < 0 ? 0 : startIndex
    
    if (startIndex > string.length) return -1

    if (string === subString) return 0
    
    let res = -1
    for (let index = startIndex; index < string.length; index++) {
        if (string.length - index >= subString.length) {
            const curString = string.slice(index, subString.length + index)
            if (curString === subString) {
                res = index
                break
            }
        }
    }
    return res
}
String.prototype.myIndexOf= function(searchValue, position = 0) {
  // 如果 position 大于字符串长度, 则不处理
  if (position > this.length) {
    return -1
  }

  // 如果 position 小于零 按 0 处理
  position = Math.max(position, 0)

  // 循环查找
  for (let i = position; i < this.length; i ++ ) {
    // 截取字符串、判断是否以指定字符串开头
    if (this.substring(i).startsWith(searchValue)) {
      return i
    }
  }

  return -1
}

const str = '0123456789'
const opt = ['4', 1]

console.log(str.myIndexOf(...opt), str.indexOf(...opt))

拿mdn上面的例子测试过了,基本没啥问题。但是实现起来有点麻烦

String.prototype.myIndexOf = function myIndexOf(searchValue, position = 0) {
  if (typeof searchValue != 'string') {
    throw new Error(`searchValue ${searchValue} 不是字符串`)
  }

  if (searchValue === '') {
    console.log(position < this.length ? position : this.length)
    return position < this.length ? position : this.length
  }

  let start = 0
  let res
  let isStart = true
  for (let i = position; i < this.length; i++) {
    const element = this[i]

    if (isStart) {
      if (element === searchValue[start]) {
        res = i
        isStart = false
      }
    }

    while (element === searchValue[start]) {
      start++
    }

    if (start >= searchValue.length) {
      console.log(res)
      return res
    }
  }

  console.log(-1)
  return -1
}
String.prototype.indexOf = function (searchValue, start = 0) {
  if (typeof searchValue !== "string") {
    throw new Error("type error");
  }
  const len = searchValue.length;
  for (let i = start; i < this.length; i++) {
    if (this.substring(i, i + len) === searchValue) return i;
  }
  return -1;
};
function myIndexOf(str1, str2) {
  if (str1.length === 0 || str2.length === 0) return -1
  if (str2.length > str1.length) return -1

  let compareStr = {
    str: '',
    index: 0
  }

  for (let i = 0; i < str1.length; i++) {
    for (j = i; j < i + str2.length; j++) {
      if (!str1[j]) return -1
      compareStr.str += str1[j]
      if (compareStr.str === str2) return compareStr.index
    }
    compareStr.index++
    compareStr.str = ''
  }
  return -1
}