We are 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. Our 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, we arrange them in their original order.
Example:
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 the original text.
"calm" 4 letters.
"code" 4 letters.
The solution is:
class Solution {
public String arrangeWords(String inputText) {
String text = inputText.toLowerCase();
String[] allWords = text.split("\\s+");
Map<Integer, List<String>> lengthToWordsMap = new HashMap<>();
for (int i = 0; i < allWords.length; i++) {
lengthToWordsMap.computeIfAbsent(allWords[i].length(), k -> new ArrayList<>());
lengthToWordsMap.get(allWords[i].length()).add(allWords[i]);
}
StringBuilder answerStringBuilder = new StringBuilder();
for (int length : lengthToWordsMap.keySet()) {
for (String word : lengthToWordsMap.get(length)) {
answerStringBuilder.append(answerStringBuilder.length() == 0 ? "" : " ").append(word);
}
}
String firstLetterInUppercase = answerStringBuilder.toString().substring(0, 1).toUpperCase();
String restOfSentenceInLowercase = answerStringBuilder.toString().substring(1);
String answer = firstLetterInUppercase + restOfSentenceInLowercase;
return answer;
}
}
I understand that after splitting the text and storing it in a String array, we are using a HashMap to store the length of words as the key and the words of that length as the length's values. But keys are not sorted in HashMaps so the length is not sorted either. So, after appending the words of each key (length of each word) to "sb", how are we ensuring that the words are rearranged in increasing order of their length?
Edit:
Okay, this is not my code. This was one of the solutions posted on the discussion board. This question is posted on Leetcode and the link to the question is here.
This solution passes all the 75 test cases too so I don't think this is working just by chance.