Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Kiểm tra chuỗi con có thể tạo từ chuỗi khác (subsequence) trong JavaScript

Viết hàm kiểm tra str2 có phải subsequence của str1 không (giữ thứ tự, có thể bỏ ký tự).

Ví dụ: str1='desxooajmepwele', str2='example' → true.

Ví dụ

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));

Kết quả

true