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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP