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

Viết hàm JavaScript trả true nếu phần của chuỗi 1 sắp xếp lại thành chuỗi 2

Viết hàm scramble(str1,str2) trả true nếu một phần ký tự của str1 sắp xếp lại thành str2.

Ví dụ:

str1='cashwool', str2='school' → true str1='katas', str2='steak' → false

Cách: split+sort 2 chuỗi, kiểm tra chuỗi nhỏ có là substring của chuỗi lớn.

Ví dụ

const str1 = 'cashwool'; const str2 = 'school'; const scramble = (str1, str2) => {    const { length: len1 } = str1;    const { length: len2 } = str2;    const firstSortedString = str1.split("").sort().join("");    const secondSortedString = str2.split("").sort().join("");    if(len1 > len2){       return firstSortedString.includes(secondSortedString);    }    return secondSortedString.includes(firstSortedString); }; console.log(scramble(str1, str2));

Kết quả

Đầu ra console:

true