




Sponsored
Sponsored
This approach involves splitting the given string into words, reversing each word individually, and then joining them back together.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), as only a constant amount of extra space is used.
1#include <iostream>
2#include <string>
3#include <algorithm>
4
5void reverseWords(std::string &s) {
6    size_t start = 0, end;
7    while ((end = s.find(' ', start)) != std::string::npos) {
8        std::reverse(s.begin() + start, s.begin() + end);
9        start = end + 1;
10    }
11    std::reverse(s.begin() + start, s.end());
12}
13
14int main() {
15    std::string s = "Let's take LeetCode contest";
16    reverseWords(s);
17    std::cout << s << std::endl;
18    return 0;
19}In this C++ solution, we use the standard library function find to locate spaces in the string. Each word is reversed using the std::reverse function.
In this C solution, a two-pointer technique is applied to reverse individual words within the string in place, using a helper function.