557. Reverse the word III in the string


The title


Given a string, you need to reverse the character order of each word in the string, while still preserving the Spaces and the original order of the words.

Example:

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

Tip:

  • In a string, each word is separated by a single space, and there are no extra Spaces in the string.

Their thinking


Use auxiliary lists

Given a string containing Spaces, reverse the words separated by Spaces, but preserve the original order of Spaces and words.

The string is separated by a single space per word, and the string has no additional Spaces.

Since there is only a single space to separate, here we can consider splitting the given string by space, using the string split() function:

  • Split strings by Spaces;
  • Define the auxiliary list, and then flip the words of the split part and add them to the auxiliary list in order;
  • Finally, the words after the inversion are concatenated and space gaps are added.

The specific code is as follows:

class Solution:
    def reverseWords(self, s: str) - >str:
        Cut according to space
        s = s.split(' ')
        # Then flip over each part of the cut
        ans = []
        for part in s:
            part = part[::-1]
            ans.append(part)

        # Final splicing
        return ' '.join(ans)
Copy the code

The previous method uses the split() method of the string, but here’s another way to do it without splitting:

  • Iterate over the string, define the variables left and right to point to the beginning and end of the word respectively, define the auxiliary list;
  • Move right, look for Spaces, and when you encounter Spaces, start adding words in reverse order to the helper list;
  • Then it encounters a space, adds that space to the helper list, and moves right again, repeating the previous steps until right reaches the end of the string.

The specific code is as follows.

class Solution:
    def reverseWords(self, s: str) - >str:
        ans = []
        length = len(s)
        
        right = 0
        while right < length:
            left = right
            Find the space, then swap before the space
            while right < length ands[right] ! =' ':
                right += 1
            Add to the auxiliary list in reverse order
            for i in range(right-1, left-1, -1):
                ans.append(s[i])
            # Add Spaces to the list when you encounter them, and move on
            while right < length and s[right] == ' ':
                ans.append(' ')
                right += 1
        
        # returns
        return ' '.join(ans)
Copy the code

Welcome to attention


Public Account [Collection of Books]