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.
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)
1using System;
2
public class Solution {
public static void ReverseWords(string s) {
char[] arr = s.ToCharArray();
int start = 0;
for (int end = 0; end <= arr.Length; end++) {
if (end == arr.Length || arr[end] == ' ') {
Reverse(arr, start, end - 1);
start = end + 1;
}
}
Console.WriteLine(new String(arr));
}
private static void Reverse(char[] arr, int start, int end) {
while (start < end) {
char temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
public static void Main() {
string s = "Let's take LeetCode contest";
ReverseWords(s);
}
}This C# solution employs a character array to facilitate in-place string alterations, utilizing boundary markers for word demarcation and character swapping within words.