Reverse Words in a String III

String Simulation

Problem

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.

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

For example:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Thought Process

  • This question is similar to Reverse Words in a String except here we aren't reversing the words of the sentence, only the letters of each word

Solution

class Solution:
    def reverseWords(self, s: str) -> str:
        s = list(s)
        j = 0
        i = 0
        
        while i < len(s):
            while i < len(s) and s[i] != ' ':
                i+=1
            
            s[j:i] = s[j:i][::-1]
         
            i+=1
            j = i
        return("".join(s))

Time Complexity

  • Time: O(n)

  • Space: O(1)

Last updated