




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
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 <stdio.h>
2
3void reverse(char* start, char* end) {
4    while (start < end) {
5        char temp = *start;
6        *start = *end;
7        *end = temp;
8        start++;
9        end--;
10    }
11}
12
13void reverseWords(char* s) {
14    char* wordStart = s;
15    char* temp = s;
16
17    while (*temp) {
18        temp++;
19        if (*temp == ' ' || *temp == '\0') {
20            reverse(wordStart, temp - 1);
21            wordStart = temp + 1;
22        }
23    }
24}
25
26int main() {
27    char str[] = "Let's take LeetCode contest";
28    reverseWords(str);
29    printf("%s\n", str);
30    return 0;
31}In this C solution, a two-pointer technique is applied to reverse individual words within the string in place, using a helper function.
Solve with full IDE support and test cases