SoFunction
Updated on 2024-10-29

The python3 implementation of flipping word dots in a string

Given a string, flip each word in the string one by one.

Description:

No space characters form a word.
Input strings can be preceded or followed by extra spaces, but reversed characters cannot be included.
If there are extra spaces between two words, reduce the spaces between the reversed words to contain only one.

Example 1:

Type: "the sky is blue".
Output: "blue is sky the"

Example 2:

Type: " hello world!"
Output: "world! hello"
Explanation: Input strings can be preceded or followed by extra spaces, but reversed characters cannot be included.

Example 3:

Enter: "a good example"
Output: "example good a"
Explanation: If there are extra spaces between two words, reduce the spaces between words after reversal to contain only one.

Example 4:

Input: s = " Bob Loves Alice "
Output: "Alice Loves Bob"

Example 5:

Input: s = "Alice does not even like bob"
Output: "bob like even not does Alice"

Thought 1:

Conventional thinking: use firststrip()The function removes the first and last spaces; note in particular that there may be more than one space in the middle. The use of double pointers, traversing the string from back to back, the first space encountered, back one to the position of j will take out a string.

在这里插入图片描述

在这里插入图片描述

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

Thought 2:

在这里插入图片描述

class Solution:
 def reverseWords(self, s: str) -> str:
  s = ()
  s = ()
  ()
  return ' '.join(s)

to this article on python3 flip string in the word point of the realization of the article is introduced to this, more related python3 flip string content, please search my previous posts or continue to browse the following related articles I hope you will support me in the future more!