Algorithm/Codewars
[Codewars/JS] Two to One
hyebin Lee
2022. 1. 13. 16:53
Details
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"
<code>
function longest(s1, s2) {
const str = "".concat(s1, s2); //str 두개를 합친다.
const uniqueStr = [...new Set(str)].sort().join(""); //합친 str을 배열로 바꾼 후 중복 제거를 하고 정렬 후 다시 str로 합친다.
console.log(uniqueStr);
return uniqueStr;
}
longest("aretheyhere", "yestheyarehere");
<other code>
function longest(s1, s2) {
s3 = s1 + s2;
console.log(s3);
//문자열을 합친다.
s4 = s3.split("");
//한 단어 씩 배열로 만들어 넣어준다.
s4 = s4.sort().filter(function (element, index, array) {
return element !== array[index - 1];
});
//정렬 후 중복을 제거한다.
console.log(s4);
return s4.join("");
//다시 문자열로 만들어준다.
}
문자열을 그냥 +로 합칠 수 있다는 방법이 놀라웠다!
다른 사람 코드를 비교하는 것이 상당히 나한테 도움이 되는 것 같았다.
filter함수와 set 함수를 다시 한번 정리 할 수 있었다.😁