1451. Rearrange Words in a Sentence
Explanation
To solve this problem, we need to rearrange the words in the sentence based on their lengths in increasing order. If two words have the same length, we need to maintain their original order. The approach involves splitting the sentence into words, sorting the words based on their lengths, and then joining them back into a new sentence.
- Split the given sentence into words.
- Create a custom comparator to sort the words based on their lengths.
- Sort the words using the custom comparator.
- Join the sorted words to form the rearranged sentence.
Time Complexity: O(n log n) where n is the number of words in the sentence. Space Complexity: O(n) where n is the number of words in the sentence.
import java.util.*;
class Solution {
public String arrangeWords(String text) {
String[] words = text.toLowerCase().split(" ");
Arrays.sort(words, (a, b) -> a.length() - b.length());
String result = String.join(" ", words);
return Character.toUpperCase(result.charAt(0)) + result.substring(1);
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.