본문 바로가기
코테연습

32.Your order, please

by hxunz 2022. 4. 7.

Description:

Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.

Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).

If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.

Examples

"is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2"  -->  "Fo1r the2 g3ood 4of th5e pe6ople"
""  -->  ""

function order(words){
  const word = words.split(' ');
  let num = [];

  for (i=0; i < word.length; i++) {
    num[word[i].match(/[1-9]/)] = word[i]
  }
  num.shift();
  
  return num.join(' ');
}

먼저 주어진 단어를 공백을 기준으로 split()을 사용해서 잘라주었다. 

const word = words.split(' ');

그리고 num을 빈 배열로 선언해둔다음에

let num = [];

for문을 돌면서 num안에 숫자 순서대로 넣어주기 위해서 match를 사용했다.

num[word[i].match(/[1-9]/)]

word[i]에서 1-9중에 해당되는 숫자를 찾고 숫자 순서대로 num에 shift()를 사용해서 넣어주었다. 

for (i=0; i < word.length; i++) {
  num[word[i].match(/[1-9]/)] = word[i]
}
num.shift();

num에 배열로 담겨있기 때문에 join()을 사용해서 다시 공백을 기준으로 string으로 리턴되게끔 정렬해주었다. 

return num.join(' ');

'코테연습' 카테고리의 다른 글

34.Decode the Morse code  (0) 2022.04.08
33.Tribonacci Sequence  (0) 2022.04.07
31.Replace With Alphabet Position  (0) 2022.04.07
30.Persistent Bugger.  (0) 2022.04.04
29.Take a Ten Minutes Walk  (0) 2022.04.04

댓글