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.
1function reverseWords(s) {
2 let words = s.split(' ');
3 let reversedWords = words.map(word => word.split('').reverse().join(''));
4 return reversedWords.join(' ');
5}
6
7let s = "Let's take LeetCode contest";
8console.log(reverseWords(s));Javascript solution uses split, map, and join functions to reverse each word. It's simple yet efficient.
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.