Skip to content

Latest commit

 

History

History
79 lines (63 loc) · 2.24 KB

1451.Rearrange Words in a Sentence.md

File metadata and controls

79 lines (63 loc) · 2.24 KB

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

  • mine
    • Java

      Runtime: 33 ms, faster than 33.33%, Memory Usage: 50.7 MB, less than 100.00% of Java online submissions

      public String arrangeWords(String text) {
          String[] item = text.toLowerCase().split(" ");
          if (item.length <= 1) {
              return text;
          }
          Arrays.sort(item, new Comparator<String>() {
              @Override
              public int compare(String o1, String o2) {
                  return o1.length() - o2.length();
              }
          });
          
          String s = item[0];
          if (s.charAt(0) >= 'a') {
              String temp = s.substring(0, 1);
              s = temp.toUpperCase() + s.substring(1);
          }
          item[0] = s;
      
          StringBuilder sb = new StringBuilder();
          for (String v : item) {
              sb.append(v).append(" ");
          }
          String res = sb.toString();
          return res.substring(0, res.length() - 1);
      }