The next challenge I am going to explain is how to reverse the words in a String. This one is a little bit tricky because we have to take into account the whitespace and the initial order of the words. Below we have the challenge:
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
The first step I will take is to split the given String to a list of words. To create the list of words, I will use the split() method from the Python library.
wordsList = s.split(" ")
If the given String is “Today we are reversing the words in a String.”, for example, the wordsList variable will be: [“Today”, “we”, “are”, “reversing”, “the”, “words”, “in”, “a”, “String.”]. Once we have the list of words, all that is left is to loop over the list and reverse each word from the list.
newStr = ' '.join([word[::-1] for word in wordsList])
The above line takes each word from the list, reverses it and then joins them together with the whitespace. I will split the line in a number of steps:
for word in wordsList
As we already know, at each iteration, the variable word will be “Today”, then “we”, then “are” and so on.
This can also be read as word[startingIndex, endingIndex, step]. I do not give any values for the starting and ending indexes, so it will use the default ones. In the example of “Today” the startingIndex is 0, and the endingIndex is 4. The -1 specifies how the word is going to be sliced at each step from the startingIndex up to the endingIndex. Thus, “Today” becomes “yadoT“.
To solve the challenge, I will use one more method from the Python library – join(). This method takes objects such as Lists, Tuples, Dictionaries, Sets and Strings. The common characteristic of this type of objects is that they can return one item at a time. In this case, I am passing the list of reversed words.
All that it does is to join the reversed words while preserving the whitespace between the words. (Notice the space between the quotes)
Now it’s time to put the solution together. The full solution is below:
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ # split the String into a list of words wordsList = s.split(" ") # take each word from the list of words # reverse the word [::-1] # join the reversed word with the white space to form the reversed String newStr = ' '.join([word[::-1] for word in wordsList]) return newStr
The statistics of this solution are embedded below. If you have better solutions or improvements, drop a comment.