Two to One

题目

Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters,

each taken only once - coming from s1 or s2.

Examples:
a = “xyaabbbccccdefww”
b = “xxxxyyyyabklmopq”
longest(a, b) -> “abcdefklmopqwxy”

a = “abcdefghijklmnopqrstuvwxyz”
longest(a, a) -> “abcdefghijklmnopqrstuvwxyz”

思路

组合两个字符串,遍历字符串检查是否存在,不存在的塞到新字符串里,最后排序。

答案

1
2
3
4
5
6
7
8
9
10
function longest(s1, s2) {
var str = s1 + s2;
var str2 = "";
for (var i in str) {
if (str2.indexOf(str[i]) === -1) {
str2 += str[i];
}
}
return str2.split("").sort().join("");
}