class Solution:
def sortSentence(self, s: str) -> str:
words = s.split()
# Create a list of (index, word) tuples
sorted_words = sorted(words, key=lambda w: int(w[-1]))
# Remove the trailing digit and join
return ' '.join(word[:-1] for word in sorted_words)
class Solution {
public:
string sortSentence(string s) {
vector<string> words;
stringstream ss(s);
string word;
while (ss >> word) {
words.push_back(word);
}
vector<string> res(words.size());
for (const auto& w : words) {
int idx = w.back() - '1';
res[idx] = w.substr(0, w.size() - 1);
}
string ans;
for (int i = 0; i < res.size(); ++i) {
if (i > 0) ans += " ";
ans += res[i];
}
return ans;
}
};
class Solution {
public String sortSentence(String s) {
String[] words = s.split(" ");
String[] res = new String[words.length];
for (String word : words) {
int idx = word.charAt(word.length() - 1) - '1';
res[idx] = word.substring(0, word.length() - 1);
}
return String.join(" ", res);
}
}
var sortSentence = function(s) {
let words = s.split(' ');
let res = Array(words.length);
for (let word of words) {
let idx = parseInt(word[word.length - 1]) - 1;
res[idx] = word.slice(0, -1);
}
return res.join(' ');
};
Given a shuffled sentence s
containing words, where each word has a single digit at its end representing its position in the original sentence, your task is to reconstruct the sentence in the correct order. The digits range from 1 to the number of words, and every word includes exactly one such digit at the end. You must return the sentence with words in the correct order, separated by single spaces, and without the digits.
Constraints:
The problem essentially asks us to reorder a list of words based on a numeric suffix. At first glance, a brute-force approach might involve repeatedly searching for the next word in order, but this would be inefficient. Instead, we should take advantage of the fact that each word ends with a unique position digit, and the number of words is known and small.
The key realization is that by extracting the digit from each word, we can directly place the word (minus the digit) into its correct position in a new array or list. This shifts the problem from searching and sorting to a simple mapping based on indices, which is much faster and easier to implement.
Let's break down the solution into clear steps:
split()
function to divide the sentence into individual words.This approach is efficient because it processes each word only once and uses direct indexing for placement.
Example Input: "is2 sentence4 This1 a3"
["is2", "sentence4", "This1", "a3"]
["This", "is", "a", "sentence"]
"This is a sentence"
Each word is placed directly at its corresponding index, making the reconstruction straightforward and efficient.
Brute-force approach:
n
is the number of words.The optimized solution is linear in both time and space because each word is handled exactly once and stored in a new list.
The problem leverages unique numeric suffixes to efficiently reconstruct the original sentence. By mapping each word to its intended position using the digit, we avoid unnecessary searching or sorting. The solution is both simple and optimal, requiring only a single traversal and direct placement, which makes it a great example of using indexing and mapping to solve ordering problems efficiently.