Reverse every words in a string.

We are giving a string. We are required to reverse the words in such a way that each words are reversed while still maintaining the position of the words and spaces in the string. For example, for the input string Let's take LeetCode contest , the output string is s'teL ekat edoCteeL tsetnoc


Solution

This should be a strightforward solution. In the following example, we iterate through the string to see for an space character. If there is a space character, we append the word tmp_str accumulated until now into the string by reversing the order.

def reverseWords(self, s: str) -> str: ret_str = '' tmp_str = '' for i in s: if i == ' ': ret_str += (tmp_str[::-1]+" ") tmp_str = '' else: tmp_str += i return ret_str + tmp_str[::-1]