[LeetCode/정렬] 1859. Sorting the Sentence(JavaScript)

jeongjin Kim·2021년 10월 26일
1

문제설명

sentence는 하나의 빈칸으로 분리된 단어들의 목록입니다.
sentence는 마지막의 하나의 숫자를 더하고 섞여 있습니다.

예) "This is a sentence" => "is2 sentence4 This1 a3"

9개 이하의 단어로 이루어진 섞인 sentense s를 원본 sentence로 바꾸어 return해주세요.

제한사항

  • 2 <= s.length <= 200
  • s consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.
  • The number of words in s is between 1 and 9.
  • The words in s are separated by a single space.
  • s contains no leading or trailing spaces.

입출력 예

Input: s = "is2 sentence4 This1 a3"
Output: "This is a sentence"
Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.

풀이

  1. 먼저 s.split(" ")을 사용해서 각각의 단어들을 배열에 넣어줍니다.
  2. for문을 사용해서 각 단어의 마지막 숫자들을 저장 합니다.
  3. 저장한 숫자들을 index로 사용해서 새로운 array에 해당 값을 저장합니다(이때 slice를 사용해서 마지막 숫자를 제거해 줍니다).
  4. 새로운 array를 join(" ")해주고 return 합니다.

코드

var sortSentence = function(s) {
    let array = [];
    let split = s.split(" ")
    for(i=0;i<split.length;i++) {
    // 해당 단어의 마지막 숫자를 indexVal에 저장
    // 예) sentence4 => indexVal = 4
        let indexVal = split[i][split[i].length-1]
        array[indexVal-1] = split[i].slice(0,split[i].length-1);
    }
    return array.join(" ");
}

0개의 댓글