LeetCode 코딩 문제 2021/07/13 - Rearrange Words in a Sentence

이호현·2021년 7월 13일
0

Algorithm

목록 보기
127/138

[문제]

Given a sentence text (A sentence is a string of space-separated words) in the following format:

  • First letter is in upper case.
  • Each word in text are separated by a single space.

Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.

Return the new text following the format shown above.

Example 1:

Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.

Example 2:

Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Explanation: Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.

Example 3:

Input: text = "To be or not to be"
Output: "To be or to be not"

(요약) 문장의 단어들을 단어 길이로 오름차순 해서 재정렬해라.
길이가 같으면 원래 순서대로 정렬.

[풀이]

var arrangeWords = function(text) {
  const splitArr = text.toLowerCase().split(' ');
   
  splitArr.sort((a, b) => a.length - b.length);
   
  return splitArr.map((str, idx) => {
    if(!idx) {
      return str[0].toUpperCase() + str.slice(1);
    }
    else {
      return str;
    }
  }).join(' ');
};

문장의 알파벳들을 소문자로 바꾸고, split(' ')을 이용해 단어별로 잘라서 배열을 만든다.

그리고 각 단어의 길이로 정렬을 한다.

마지막으로 첫 번째로 나오는 단어이면 첫 알파벳만 대문자로 바꿔준다.

profile
평생 개발자로 살고싶습니다

0개의 댓글