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

  • Blank characters form a word.
  • An input string can contain extra Spaces before or after it, but not inverted characters.
  • If there is extra space between two words, reduce the space between the inverted words to only one.

Example 1:

Input:"the sky is blue"Output:"blue is sky the"
Copy the code

Example 2:

Input:" hello world! "Output:"world! hello"Explanation: The input string can contain extra Spaces before or after it, but cannot contain inverted characters.Copy the code

Example 3:

Input:"a good example"Output:"example good a"Explanation: If there is extra space between two words, reduce the space between the inverted words to only one.Copy the code

Example 4:

Enter: s =" Bob Loves Alice "Output:"Alice Loves Bob"
Copy the code

Example 5:

Enter: s ="Alice does not even like bob"Output:"bob like even not does Alice"
Copy the code

Tip:

  • 1 <= s.length <= 104
  • S contains uppercase and lowercase letters, digits, and Spaces.
  • There is at least one word in s

Flipping the non-null characters in a given string returns the normal string format. The resulting string cannot start or end with a space, and each word is separated by a space. Java solution code is as follows:

class Solution {
    public String reverseWords(String s) {
        String[] strs = s.trim().split("");
        String res = new String();
        for(int i = strs.length - 1; i >= 0; i--) {
            if(! strs[i].equals("")){
                res = res + strs[i] + ""; }}returnres.trim(); }}Copy the code

Or use StringBuilder or StringBuffer for concatenating strings and call toString() when it returns.

class Solution {
    public String reverseWords(String s) {
        String[] strs = s.trim().split("");
        StringBuilder res = new StringBuilder();
        for(int i = strs.length - 1; i >= 0; i--) {
            if(! strs[i].equals("")){
                res.append(strs[i] + ""); }}returnres.toString().trim(); }}Copy the code

Python’s solution is even simpler, with a call to split() separating each element with no space before or after it. Finally, use join() to concatenate Spaces:

class Solution:
    def reverseWords(self, s: str) - >str:
        if not str: return ' ' # the must
        
        return ' '.join(s.strip().split()[::-1])
Copy the code