# 53.Reverse Words in a String

## 1.Description(Easy)

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

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

**Clarification**

* What constitutes a word?\
  A sequence of non-space characters constitutes a word.
* Could the input string contain leading or trailing spaces?\
  Yes. However, your reversed string should not contain leading or trailing spaces.
* How about multiple spaces between two words?\
  Reduce them to a single space in the reversed string.

## 2.Code

用split函数将string分成一个一个单词，在从后往前一次append到stringbuilder中，注意最后检查下是否remove last space,但是test中不加这个检查也能pass。

```
public String reverseWords(String s){
        if(s==null || s.length()==0){
            return "";
        }
        StringBuilder result=new StringBuilder();
        String[] str=s.split(" ");
        for(int i=str.length-1;i>=0;i--){
            if(!str[i].equals("")){
                result.append(str[i]).append(" ");
            }
        }
        //remove the last " "
        if(result.length()==0){
            return "";
        }else{
            return result.toString();
        }

    }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://junnie.gitbook.io/amazon-mock-interview/phone-interview-i/readme.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
