> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/557.reverse_words_in_a_string.md).

# 557.Reverse Words in a String

**557.Reverse Words in a String**

难度:Easy

> 给定一个字符串，你需要反转字符串中每个单词的字符顺序，同时仍保留空格和单词的初始顺序。

示例 1: 输入: "Let's take LeetCode contest" 输出: "s'teL ekat edoCteeL tsetnoc" 注意：在字符串中，每个单词由单个空格分隔，并且字符串中不会有任何额外的空格。

代码如下：

```
class Solution {
public:
    string reverseWords(string s) {
        vector<string> words;
        words.push_back(" ");
        for(auto w:s)
        {
            if(w==' ')
            {               
                words.push_back(" ");            
            }
            else
                words[words.size()-1]+=w;
           // cout<< words[words.size()-1]<<endl;
        }
        words[words.size()-1]=words[words.size()-1].substr(1,words[words.size()-1].length()-1);
      //  cout<< words[0]<<words[1]<<endl;
       // words[words.size()-1]+=' ';
        string res;
        for(auto w:words)
        {
            for(int i=w.length()-1;i>=0;i--)
            {
                res+=w[i];
         //       cout<<res;
            }
        }
        return res;
    }
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://dfine.gitbook.io/leetcode/557.reverse_words_in_a_string.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
