Reverse Words in a String

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.

Example 1:

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.


def reverseWords(self, s):
    s = s.split(" ")

    for words in range(0,len(s)):
        s[words] = s[words][::-1]

    s = ' '.join(s)
    return s

Developer’s Notes 👨‍💻

Here I took advantage of what python had to offer such as the split and join methods.

I first split the string where there was a ” ” and put them into a list.

I then cycled through the list reassigning the index with the reverse of the word.

    I reversed the word using a reverse step method s[begin:end: step] with step being -1

After I had reversed all the words I joined them back into a string with a space between each index.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s