15 Jun 2024C++ / Python / TypeScriptEasy

Reverse Words in a String III

Collected C++, Python, TypeScript solutions for reverse words in a string iii. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Reverse Words in a String III. the solution files are available below.

solution files

  • C++ reverse-words-in-a-string-iii/synced-solution.cpp
  • Python reverse-words-in-a-string-iii/synced-solution.py
  • TypeScript reverse-words-in-a-string-iii/synced-solution.ts

Solution files

Pythonreverse-words-in-a-string-iii/synced-solution.py
class Solution:
    def reverseWords(self, s: str) -> str:
        return class="syntax-string">" ".join(word[::-class="syntax-number">1] for word in s.split(class="syntax-string">" "))
C++reverse-words-in-a-string-iii/synced-solution.cpp
class Solution {
public:
    string reverseWords(string s) {
        stringstream stream(s);
        string word;
        string result;

        while (stream >> word) {
            reverse(word.begin(), word.end());
            if (!result.empty()) {
                result += class="syntax-string">' ';
            }
            result += word;
        }
        return result;
    }
};
TypeScriptreverse-words-in-a-string-iii/synced-solution.ts
function reverseWords(s: string): string {
    return s
        .split(class="syntax-string">" ")
        .map(word => word.split(class="syntax-string">"").reverse().join(class="syntax-string">""))
        .join(class="syntax-string">" ");
}