




Sponsored
Sponsored
This approach involves splitting the original string into individual words using space as a delimiter, reversing the list of words, and then joining them back together with a single space.
Time Complexity: O(N), where N is the length of the string, as we process each character once.
Space Complexity: O(N), additional space for intermediate and result storage.
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4
5char* reverseWords(char *s) {
6    // calculate length
7    int len = strlen(s), start = 0, wordCount = 0;
8    char *temp = malloc(len + 1);
9    char *result = malloc(len + 1);
10    temp[0] = '\0'; result[0] = '\0';
11    
12    // trim leading and trailing spaces
13    while (s[start] == ' ') start++;
14    int end = len - 1;
15    while (s[end] == ' ') end--;
16    
17    for (int i = start; i <= end; i++) {
18        if (s[i] != ' ') {
19            strncat(temp, &s[i], 1);
20        } else if (s[i] == ' ' && (i == start || s[i - 1] != ' ')) {
21            strcat(temp, " ");
22        }
23    }
24    char *token = strtok(temp, " ");
25    while (token != NULL) {
26        if (wordCount > 0) {
27            memmove(result + strlen(token) + 1, result, strlen(result) + 1);
28            memcpy(result, " ", 1);
29        }
30        memmove(result + strlen(token), result, strlen(result) + 1);
31        memcpy(result, token, strlen(token));
32        token = strtok(NULL, " ");
33        wordCount++;
34    }
35    free(temp);
36    return result;
37}
38
39int main() {
40    char input[] = "  hello world  ";
41    char* output = reverseWords(input);
42    printf("%s\n", output);
43    free(output);
44    return 0;
45}The C solution involves:
strtok() to split the string by spaces into separate words.This optimized approach manipulates the string in place by using a character array. We'll first reverse the entire string, and then reverse each word to return them to their correct order.
Time Complexity: O(N), where N is the number of characters in the string.
Space Complexity: O(1), as the operation is done in-place without extra space.
1public
The Java solution reverses the whole string initially, then processes each word by reversing it again in place while constructing a new word order with correct spacing.