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.
1using System;
2
3public class Solution {
4 public static void ReverseWords(string s) {
5 char[] arr = s.ToCharArray();
6 int start = 0;
7
8 for (int end = 0; end < arr.Length; end++) {
9 if (arr[end] == ' ' || end == arr.Length - 1) {
10 Reverse(arr, start, (end == arr.Length - 1) ? end : end - 1);
11 start = end + 1;
12 }
13 }
14 Console.WriteLine(new String(arr));
15 }
16
17 private static void Reverse(char[] arr, int start, int end) {
18 while (start < end) {
19 char temp = arr[start];
20 arr[start] = arr[end];
21 arr[end] = temp;
22 start++;
23 end--;
24 }
25 }
26
27 public static void Main() {
28 string s = "Let's take LeetCode contest";
29 ReverseWords(s);
30 }
31}In this C# implementation, the solution uses an array to manipulate the string and reverses each word using a helper function.
In this Python solution, the string is first converted into a list to allow in-place modifications. Then, a custom reverse function swaps the word's elements in-place.