如何編寫一個 JavaScript 函式,它能夠判斷字串 1 的一部分是否可以透過重新排列字元來構成字串 2?
我們需要編寫一個函式,如果字串 1 的一部分可以重新排列成字串 2,則返回 true。編寫一個函式,例如 scramble(str1,str2),如果 str1 字元的一部分可以重新排列以匹配 str2,則返回 true,否則返回 false。
例如 -
Let’s say string1 is str1 and string2 is str2. str1 is 'cashwool' and str2 is ‘school’ the output should return true. str1 is 'katas' and str2 is 'steak' should return false.
因此,以下是執行此操作的程式碼。我們只需拆分並排序兩個字串,然後檢查較小的字串是否為較大字串的子字串。
執行此操作的完整程式碼如下 -
示例
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));輸出
控制檯中的輸出將是 -
true
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP