Formatted question description: https://leetcode.ca/all/1451.html

1451. Rearrange Words in a Sentence

Level

Medium

Description

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”

Constraints:

  • text begins with a capital letter and then contains lowercase letters and single space between words.
  • 1 <= text.length <= 10^5

Solution

First, convert text to lower case letters. Next, split text into an array using spaces. Then sort array according to words’ lengths in ascending order.

After sorting, concatenate the words to form the new text, and convert the first letter in the new text to the upper case letter. Finally, return the new text.

class Solution {
    public String arrangeWords(String text) {
        text = text.toLowerCase();
        String[] array = text.split(" ");
        Arrays.sort(array, new Comparator<String>() {
            public int compare(String str1, String str2) {
                return str1.length() - str2.length();
            }
        });
        int length = array.length;
        StringBuffer sb = new StringBuffer();
        sb.append(array[0]);
        sb.setCharAt(0, (char) (array[0].charAt(0) - ('a' - 'A')));
        for (int i = 1; i < length; i++) {
            sb.append(' ');
            sb.append(array[i]);
        }
        return sb.toString();
    }
}

All Problems

All Solutions