Question
Given an input string, reverse the string word by word.

For example,
Given s = ​​`​"the sky is blue"​`​​,
return ​​`​"blue is sky the"​`​.

1、API

【复杂度】

【思路】

【注意】

1. 先用trim()将前后无用的空格去掉
2. 用正则表达式” +”来匹配一个或多个空格

【代码】

`public class Solution {    public String reverseWords(String s) {        String[] words = s.trim().split(" +");        int len = words.length;        StringBuilder result = new StringBuilder();        for(int i = len -1; i>=0;i--){            result.append(words[i]);            if(i!=0) result.append(" ");        }        return result.toString();    }}`

2、双指针交换法

【复杂度】

【思路】

【代码】

`public class Solution {    public String reverseWords(String s) {        s = s.trim();        char[] str = s.toCharArray();        // 先反转整个数组        reverse(str, 0, str.length - 1);        int start = 0, end = 0;        for(int i = 0; i < s.length(); i++){            if(str[i]!=' '){                end++;            } else {                // 反转每个单词                reverse(str, start, end - 1);                end++;                start = end;            }        }        return String.valueOf(str);    }    public void reverse(char[] str, int start, int end){        while(start < end){            char tmp = str[start];            str[start] = str[end];            str[end] = tmp;            start++;            end--;        }    }}`

## 参考

​​
[Leetcode] Reverse Words in a String 反转单词顺序​​