> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/151.-reverse-words-in-a-string.md).

# 151. Reverse Words in a String

## 1.問題

![](/files/-LabpS_PIa2CY7ubVp_M)

## 2.想法&#x20;

## 3.程式碼

```
class Solution {
public:
    string reverseWords(string s) {
        if (s.empty()) {
            return s;
        }
        
        int size = s.length(), last = 0, cur = 0;
        vector<string> res;
        for(int i = 0 ; i < size; i++) {
            if (s[i] == ' ') {
                if (!s.substr(last, i - last).empty()) {
                    res.push_back(s.substr(last, i - last));
                }
                last = i+ 1;
            }
        }
        if (!s.substr(last, size).empty()) {
            res.push_back(s.substr(last, size));
        }
        
        string ss = "";
        for(int i = res.size() - 1 ; i > 0; i--) {
            ss = ss + res[i] + " ";
        }
        if (!res.empty()) {
            ss += res[0];
        }
        
        return ss;
    }
};
```

##
