首页 > 解决方案 > 搜索字符串自定义函数算法

问题描述

我想调整我输入值(“ello”)和变量(“hello”)的字符串。

如果在 string("hello") 中找到它,则返回值应该是 "ello"。如果没有找到,返回值应该是-1。

但由于条件(strs[i] == arrayS[tempVal]) ,它返回了 4 次“llll” 。

我怎样才能得到上面提到的正确答案?

var stres = "hello";
var strs = [...stres];

function searchStr(s) {
  let arrayS = [...s];
  let tempVal = 0;
  let tempStr = [];
  while (tempVal < arrayS.length) {
    for (let i = 0; i < strs.length; i++) {
      if (strs[i] == arrayS[tempVal]) {
        tempStr.push(arrayS[tempVal]);
      }
    }
    tempVal++;
  }

  return tempStr;
}

const res = searchStr("ello");
console.log('res', res)

标签: javascriptalgorithm

解决方案


根据您的说法,逻辑是正确的,只需在满足条件时打破 for 循环即可。检查下面的代码段和控制台输出。

var stres = "hello";
var strs = [...stres];

function searchStr(s) {
  let arrayS = [...s];
  let tempVal = 0;
  let tempStr = [];
  while (tempVal < arrayS.length) {
    for (let i = 0; i < strs.length; i++) {
      if (strs[i] == arrayS[tempVal]) {
        tempStr.push(arrayS[tempVal]);
        break;
      }
    }
    tempVal++;
  }
  return tempStr;
}

const res = searchStr("ello");
const resS = res.join('');
console.log('res = ', res);
console.log('resS = ', resS);


推荐阅读