
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.
1using System;
2
3public class Solution {
4 public static string ReverseWords(string s) {
5 string[] words = s.Trim().Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
6 Array.Reverse(words);
7 return string.Join(" ", words);
8 }
9
10 public static void Main() {
11 string input = " hello world ";
12 string output = ReverseWords(input);
13 Console.WriteLine(output);
14 }
15}In C#, the solution employs Trim() to handle spaces and Split() to handle empty substrings when splitting. The Array.Reverse() is used for reversing the split words before joining them with a space as the delimiter.
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.
1using System.Text;
public class Solution {
public static string ReverseWords(string s) {
char[] chars = s.Trim().ToCharArray();
int n = chars.Length;
void Reverse(int start, int end) {
while (start < end) {
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
}
Reverse(0, n - 1);
int rightIndex = 0;
for (int i = 0; i < n; ++i) {
if (chars[i] == ' ') continue;
int start = i;
while (i < n && chars[i] != ' ') i++;
Reverse(start, i - 1);
while (start < i) chars[rightIndex++] = chars[start++];
if (rightIndex < n) chars[rightIndex++] = ' ';
}
return new String(chars, 0, rightIndex == 0 ? 0 : rightIndex - 1);
}
public static void Main() {
string input = " hello world ";
string output = ReverseWords(input);
Console.WriteLine(output);
}
}The C# solution includes reversing the whole character array initially, and then processing each token to be reversed in place before constructing the final string with correct whitespace handling.