leetcode python flip words in strings

# Leetcode 151 inverted words in strings
### Title Description
Given a string, each individually flip word string.

Example 1 **: **

Enter: "the sky is blue"
Output: "blue is sky the"

Example 2 **: **

Input: "hello world!"
Output: "! World hello"
Explanation: The input string may include extra spaces in front or back, but not including the reversed character.

Example 3 **: **

Input: "a good example"
Output: "example good a"
explanation: If there are two extra spaces between words, to reduce the space between the word inversion to only containing one.

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(s.strip().split()[::-1])   
#return " ".join([t for t in s.strip().split()][::-1]) 同样可以

s.strip () remove both spaces

s.split () to open the entire string into a list, the list each element is one of a small string, s is "hello world!", s.split () is [ "hello", " world! "]

s.join () and s.split () In contrast, split is open, join is a connection, "" .join ([ "hello", "world!"]) means that the little box with a list of string concatenation into a string, the result is "hello world!"

 

Guess you like

Origin www.cnblogs.com/hooo-1102/p/11057892.html