JavaScript 中的子字符串组合


我们需要编写一个 JavaScript 函数,该函数以两个字符串作为第一个和第二个参数。我们称这两个字符串为 str1 和 str2。此函数应检查 str2 中是否存在一个子串组合,将这些组合组合在一起会生成 str2。

就子字符串组合而言,这意味着我们可以跳过字符,但我们必须保持从 str1 中选择的字符的顺序。

例如 -

如果输入字符串为 -

const str1 = 'desxooajmepwele';
const str2 = 'example';

则输出应为 -

const output = true;

因为可以通过从 str1 中选取一些字符并保持字符的顺序来形成字符串 `example`。

示例

代码如下 -

 实时演示

const str1 = 'desxooajmepwele';
const str2 = 'example';
const containsString = (str1 = '', str2 = '') => {
   let [foundAt, next] = [0, 0];
   for(const char of str2){
      next = str1.slice(foundAt).indexOf(char);
      if (next === - 1){
         return false;
      };
      foundAt += next + 1;
   };
   return true;
};
console.log(containsString(str1, str2));

输出

控制台中的输出为 -

true

更新于: 24-02-2021

179 次浏览

开启您的 职业生涯

通过完成本课程获得认证

开始
广告
© . All rights reserved.