
Sponsored
Sponsored
This approach involves splitting the original string into individual words using space as a delimiter, reversing the list of words, and then joining them back together with a single space.
Time Complexity: O(N), where N is the length of the string, as we process each character once.
Space Complexity: O(N), additional space for intermediate and result storage.
1import java.util.ArrayList;
2import java.util.List;
3
4public class Solution {
5 public static String reverseWords(String s) {
6 String[] words = s.trim().split("\\s+");
7 StringBuilder sb = new StringBuilder();
8 for (int i = words.length - 1; i >= 0; i--) {
9 sb.append(words[i]);
10 if (i != 0) sb.append(" ");
11 }
12 return sb.toString();
13 }
14
15 public static void main(String[] args) {
16 String input = " hello world ";
17 String output = reverseWords(input);
18 System.out.println(output);
19 }
20}The Java solution uses split() with a regular expression to tokenize the input string by spaces while eliminating leading/trailing/multiple spaces. The words are stored in a reverse manner using a StringBuilder for the final output.
This optimized approach manipulates the string in place by using a character array. We'll first reverse the entire string, and then reverse each word to return them to their correct order.
Time Complexity: O(N), where N is the number of characters in the string.
Space Complexity: O(1), as the operation is done in-place without extra space.
1
This C solution reverses the string in place using a helper function reverseCharArray. It then iterates over the string, reversing individual words and reconstructing the string without additional leading or trailing spaces.