코테연습

15.Two to One

hxunz 2022. 3. 24. 17:50

Description:

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"

 

function longest(s1, s2) {
  const same = s1.concat(s2);
  const str = new Set(same);
  const result = [...str].sort();

  return result.join('');
}

먼저 주어진 두개의 단어를 concat()을 사용해서 하나로 합쳤다.

그 다음에는 Set을 사용해서 중복값을 제거해줬다.

그 다음에 sort()를 사용해서 오름차순 배열로 나타냈다.

그 다음에 이 배열을 스트링으로 나타내기 위해서 join('')을 사용했다.