Sorting the Sentence

easy string sorting

Problem

Given a shuffled sentence whose words end with their original 1-indexed position, reconstruct it.

Inputs = "is2 sentence4 This1 a3"
Output"This is a sentence"
Words bucket to positions 1..4.

def sort_sentence(s):
    words = s.split()
    out = [''] * len(words)
    for w in words:
        out[int(w[-1]) - 1] = w[:-1]
    return ' '.join(out)
function sortSentence(s) {
  const words = s.split(' ');
  const out = new Array(words.length);
  for (const w of words) {
    out[Number(w[w.length - 1]) - 1] = w.slice(0, -1);
  }
  return out.join(' ');
}
class Solution {
    public String sortSentence(String s) {
        String[] words = s.split(" ");
        String[] out = new String[words.length];
        for (String w : words) {
            int p = w.charAt(w.length() - 1) - '0';
            out[p - 1] = w.substring(0, w.length() - 1);
        }
        return String.join(" ", out);
    }
}
string sortSentence(string s) {
    vector<string> words;
    stringstream ss(s); string w;
    while (ss >> w) words.push_back(w);
    vector<string> out(words.size());
    for (auto& x : words) {
        int p = x.back() - '0';
        out[p - 1] = x.substr(0, x.size() - 1);
    }
    string result;
    for (size_t i = 0; i < out.size(); i++) { if (i) result += ' '; result += out[i]; }
    return result;
}
Time: O(n) Space: O(n)