题目链接:https://leetcode-cn.com/problems/reverse-words-in-a-string/
题目描述:
题解:
class Solution {
public:
string reverseWords(string s) {
stack <string> stk;
string word = "";
for(int i = 0; i < s.size(); i++)
{
if(s[i] != ' ')
{
word += s[i];
if(s[i + 1] == ' ' || i == s.size() - 1) //如果该单词后为空格或该单词为最后一个单词
{
stk.push(word); //单词入栈
word = "";
}
}
}
string str;
while(!stk.empty())
{
str += stk.top();
stk.pop();
if(!stk.empty()) //最后一个单词后面不加空格
str += " ";
}
return str;
}
};