Chúng ta cần viết hàm nhận hai chuỗi str1, str2. Hàm xác định có thể tạo str2 bằng cách xóa một số ký tự từ str1, không sắp xếp lại ký tự của chuỗi nào.
Ví dụ - str1 = 'sjkfampeflef', str2 = 'sample' -> true (có thể xóa bớt ký tự từ str1 để được str2).
Ví dụ
Code sau đây:
const str1 = 'sjkfampeflef';
const str2 = 'sample';
const checkConvertibility = (str1 = '', str2 = '') => {
if (!str1 || !str2) return false;
const strArr1 = str1.split('');
const strArr2 = str2.split('');
const shorter = strArr1.length < strArr2.length ? strArr1 : strArr2;
const longer = strArr1.length < strArr2.length ? strArr2 : strArr1;
for (let i = 0; i < shorter.length; i++) {
const el = shorter[i];
const index = longer.indexOf(el);
if (index !== -1) { longer.splice(index, 1); continue; }
return false;
}
return true;
};
console.log(checkConvertibility(str1, str2));Kết quả
Kết quả trên console:
true