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.
1def reverseWords(s):
2 words = s.split()
3 return ' '.join(word[::-1] for word in words)
4
5s = "Let's take LeetCode contest"
6print(reverseWords(s))In Python, we split the string into words, reverse each word, and then join them back together with spaces.
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.