JavaScript 中由兩個字串構建的最長可能字串
問題
我們需要編寫一個 JavaScript 函式,該函式接受兩個僅包含 a 到 z 字元的字串 s1 和 s2。
我們的函式應返回一個新的已排序字串,它儘可能長,包含來自 s1 或 s2 的不重複的字母——每個字母只能出現一次。
示例
程式碼如下 −
const str1 = "xyaabbbccccdefww"; const str2 = "xxxxyyyyabklmopq"; const longestPossible = (str1 = '', str2 = '') => { const combined = str1.concat(str2); const lower = combined.toLowerCase(); const split =lower.split(''); const sorted = split.sort(); const res = []; for(const el of sorted){ if(!res.includes(el)){ res.push(el) } } return (res.join('')); }; console.log(longestPossible(str1, str2));
輸出
控制檯輸出如下 −
abcdefklmopqwxy
廣告