문제
1451. Rearrange Words in a Sentence
Medium
405
57
Add to List
Share
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"
풀이
재영
const arrangeWords = (text) => { return text .toLowerCase() .split(" ") .sort((a, b) => (a.length !== b.length ? a.length - b.length : 0)) .map((val, idx) => (!idx ? val[0].toUpperCase() + val.slice(1) : val)) .join(" "); }; // faster than 46%
효성
var arrangeWords = function(text) { let answer = '', arr = []; const splited = text.split(' '); splited.forEach(str => { const length = str.length; arr.push([str.toLowerCase(), length]); }); arr.sort((a, b) => a[1] - b[1]); arr.forEach((d, i) => { if(i === 0) { answer += d[0][0].toUpperCase() + d[0].substr(1); } else { answer += ` ${d[0]}` } }); return answer; };
- substr은 Deprecated...
- 굳이 배열로 저장 안해도 될 것 같아요. 0과 1이 무엇을 나타내는지 헷갈림..
은찬
const arrangeWords = (text) => { const strings = text.split(" ").map((str) => str.toLowerCase()); strings.sort((a, b) => a.length - b.length); const joined = strings.join(" "); return joined.charAt(0).toUpperCase() + joined.slice(1); };