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.
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.