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.
1public class Solution {
2 public static void reverseWords(String s) {
3 char[] arr = s.toCharArray();
4 int n = arr.length;
5 int start = 0;
6
7 for (int end = 0; end < n; end++) {
8 if (arr[end] == ' ' || end == n - 1) {
9 reverse(arr, start, (end == n - 1) ? end : end - 1);
10 start = end + 1;
11 }
12 }
13 System.out.println(new String(arr));
14 }
15
16 private static void reverse(char[] arr, int start, int end) {
17 while (start < end) {
18 char temp = arr[start];
19 arr[start] = arr[end];
20 arr[end] = temp;
21 start++;
22 end--;
23 }
24 }
25
26 public static void main(String[] args) {
27 String s = "Let's take LeetCode contest";
28 reverseWords(s);
29 }
30}This Java solution uses a similar approach to the C solution. It reverses each word in place 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.