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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP