# LeetCode 151. Reverse Words in a String
## 題目
[LeetCode 151. Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/)
> Given an input string s, reverse the order of the words.
>
> A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
>
>Return a string of the words in reverse order concatenated by a single space.
>
>Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
## 個人解題思路
#### 將字串 `s` 以空白字元切割為數個字串放入堆疊中
#### 放入完畢後再依序使用stack函式`.top()` `.pop()`來獲得題目要求的反轉字串
## 程式碼
```cpp=
class Solution
{
public:
string reverseWords(string s)
{
string word = "";
stack<string> rev;
for (auto i : s)
{
if (i != ' ')
{
word += i;
}
else
{
if (word != "")
{
rev.push(word);
word = "";
}
}
}
if (word != "")
{
rev.push(word);
word = "";
}
while (!rev.empty())
{
word += rev.top() + " ";
rev.pop();
}
word.pop_back();
return word;
}
};
```
## 提交結果

###### tags: `LeetCode` `C++`