Skip to content

1859. Sorting the Sentence 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  string sortSentence(string s) {
    vector<string> words;
    istringstream iss(s);
    string word;

    while (iss >> word)
      words.push_back(word);

    ranges::sort(words, [](const string& a, const string& b) {
      return a.back() < b.back();
    });

    string ans = trim(words[0]);

    for (int i = 1; i < words.size(); ++i)
      ans += " " + trim(words[i]);

    return ans;
  }

 private:
  string trim(const string& s) {
    return s.substr(0, s.length() - 1);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public String sortSentence(String s) {
    String[] words = s.split(" ");

    Arrays.sort(words, (a, b) -> a.charAt(a.length() - 1) - b.charAt(b.length() - 1));

    StringBuilder sb = new StringBuilder(trim(words[0]));

    for (int i = 1; i < words.length; ++i)
      sb.append(" ").append(trim(words[i]));

    return sb.toString();
  }

  private String trim(final String s) {
    return s.substring(0, s.length() - 1);
  }
}
1
2
3
class Solution:
  def sortSentence(self, s: str) -> str:
    return ' '.join([w[:-1] for w in sorted(s.split(), key=lambda x: x[-1])])