




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 <stdio.h>
2#include <string.h>
3
4void reverseWord(char* start, char* end) {
5    while(start < end) {
6        char temp = *start;
7        *start = *end;
8        *end = temp;
9        start++;
10        end--;
11    }
12}
13
14void reverseWords(char* s) {
15    char* word_start = s;
16    char* temp = s; 
17
18    while(*temp) {
19        temp++;
20        if (*temp == ' ' || *temp == '\0') {
21            reverseWord(word_start, temp - 1);
22            word_start = temp + 1;
23        }
24    }
25}
26
27int main() {
28    char s[] = "Let's take LeetCode contest";
29    reverseWords(s);
30    printf("%s\n", s);
31    return 0;
32}This C solution involves iterating over the string and reversing each word individually. We keep track of the start of each word and reverse the word in place when we encounter a space.
This involves using a two-pointer technique to reverse the characters within each word in place, thus preserving the overall space complexity.
Time Complexity: O(n)
Space Complexity: O(1)
1#include <iostream>
2#include <vector>
#include <string>
using namespace std;
void reverseWords(string& s) {
    int i = 0;
    for(int j = 0; j <= s.size(); j++) {
        if(j == s.size() || s[j] == ' ') {
            reverse(s.begin() + i, s.begin() + j);
            i = j + 1;
        }
    }
}
int main() {
    string s = "Let's take LeetCode contest";
    reverseWords(s);
    cout << s << endl;
    return 0;
}This C++ solution uses two indices, 'i' and 'j', to track the beginning and end of each word, leveraging reverse from the algorithm library to reverse the words in place.