Leetcode 557. Reverse Words in a String III
Problem Explanation
The problem is to reverse each word in the given sentence string without changing the order of words and position of white spaces. The solution needs to handle also the multiple consecutive whitespaces. Each word in the string is separated by single space and there will not be any extra space in the string.
Walkthrough
Take the string "Let's take LeetCode contest" as an example. The idea is to go through the string one character at a time and perform following operations:
-
Find the starting index (i) and the ending index (j) of each word.
-
As we find the word, reverse all characters from index (i) to (j).
-
Repeat the first two steps for all the words.
Applying these steps, the output string would be "s'teL ekat edoCteeL tsetnoc".
The complexity of the solution is linear, which means it will take O(n) time where n is the length of the input string.
Solution
Python
1 2python 3class Solution(object): 4 def reverseWords(self, s): 5 # split the string into list of words 6 words = s.split(' ') 7 # for each word in words reverse the word 8 for i in range(len(words)): 9 words[i] = words[i][::-1] 10 # Join all the words with a space and return 11 return ' '.join(words)
Java
1
2java
3class Solution {
4 public String reverseWords(String s) {
5 String words[] = s.split(" ");
6 StringBuilder result = new StringBuilder();
7
8 for (String word : words)
9 result.append(new StringBuffer(word).reverse().toString() + " ");
10
11 return result.toString().trim();
12 }
13}
Javascript
1 2javascript 3var reverseWords = function(s) { 4 return s.split(' ').map(word => word.split('').reverse().join('')).join(' '); 5};
C++
1
2c++
3class Solution {
4public:
5 string reverseWords(string s) {
6 int i = 0, j = 0, n = s.size();
7 while (i < n) {
8 while (i < j) i++;
9 while (j < n && s[j] != ' ') j++;
10 reverse(s.begin() + i, s.begin() + j);
11 }
12 return s;
13 }
14};
C#
1
2csharp
3public class Solution {
4 public string ReverseWords(string s) {
5 var words = s.Split(' ');
6 for(var i = 0; i < words.Length; i++) {
7 var charArray = words[i].ToCharArray();
8 Array.Reverse(charArray);
9 words[i] = new string(charArray);
10 }
11 return string.Join(" ", words);
12 }
13}
Conclusion
In summary, the idea is to use the language-specific utilities and methods to split the string into words, reverse each word, and then join them back together. We took a closer look at how to implement the solution in various programming languages - Python, Java, JavaScript, C++, and C#.
Remember that in this problem, we can have multiple ways of achieving the same result. The solution is not unique and sometimes can be subjected to the different characteristics of programming languages.
Moreover, it is always a good idea to perform error checks in your code, such as making sure the input string is not null or empty, although these checks were omitted in these solutions for brevity.
The challenges to reverse words in a string may seem simple at first, but they do teach us various ways to maneuver and manipulate strings. This type of problem is a common interview question and is a great way to demonstrate your understanding of strings and how to manipulate them in various programming languages.
Finally, make sure to test your code with multiple test cases including edge cases, such as an empty string or a string with only one word. These tests will ensure the reliability of your code.
Got a question?ย Ask the Teaching Assistantย anything you don't understand.
Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.